| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.DiagonalTraverse; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class DiagonalTraverseSimulation : IDiagonalTraverse |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(m * n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="mat"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int[] FindDiagonalOrder(int[][] mat) |
| 2 | 24 | | { |
| 2 | 25 | | var m = mat.Length; |
| 2 | 26 | | var n = mat[0].Length; |
| | 27 | |
|
| 2 | 28 | | var result = new int[m * n]; |
| | 29 | |
|
| 2 | 30 | | var row = 0; |
| 2 | 31 | | var column = 0; |
| 2 | 32 | | var direction = Direction.UpRight; |
| | 33 | |
|
| 30 | 34 | | for (var i = 0; i < result.Length; i++) |
| 13 | 35 | | { |
| 13 | 36 | | result[i] = mat[row][column]; |
| | 37 | |
|
| 13 | 38 | | switch (direction) |
| | 39 | | { |
| 7 | 40 | | case Direction.UpRight when column == n - 1: |
| 3 | 41 | | row++; |
| 3 | 42 | | direction = Direction.DownLeft; |
| 3 | 43 | | break; |
| 4 | 44 | | case Direction.UpRight when row == 0: |
| 2 | 45 | | column++; |
| 2 | 46 | | direction = Direction.DownLeft; |
| 2 | 47 | | break; |
| | 48 | | case Direction.UpRight: |
| 2 | 49 | | row--; |
| 2 | 50 | | column++; |
| 2 | 51 | | break; |
| 6 | 52 | | case Direction.DownLeft when row == m - 1: |
| 2 | 53 | | column++; |
| 2 | 54 | | direction = Direction.UpRight; |
| 2 | 55 | | break; |
| 4 | 56 | | case Direction.DownLeft when column == 0: |
| 1 | 57 | | row++; |
| 1 | 58 | | direction = Direction.UpRight; |
| 1 | 59 | | break; |
| | 60 | | case Direction.DownLeft: |
| 3 | 61 | | row++; |
| 3 | 62 | | column--; |
| 3 | 63 | | break; |
| | 64 | | } |
| 13 | 65 | | } |
| | 66 | |
|
| 2 | 67 | | return result; |
| 2 | 68 | | } |
| | 69 | |
|
| | 70 | | private enum Direction |
| | 71 | | { |
| | 72 | | UpRight, |
| | 73 | | DownLeft |
| | 74 | | } |
| | 75 | | } |