C# - simple traverse logic


  • 0
        public int[] FindDiagonalOrder(int[,] matrix)
        {
            int n = matrix.GetLength(0);
            int m = matrix.GetLength(1);
            
            int len = n*m;
            int[] nums = new int[len];
            int index = 0;
            int i = 0;
            int j = 0;
            int move = 1;
            while (index < len)
            {
                nums[index++] = matrix[i,j];
                i -= move;
                j += move;
                if (j == m) 
                { 
                    i += 2;
                    j--;
                    move = -move; 
                }
                else if (i == n)
                {
                    i--;
                    j += 2;
                    move = -move; 
                }
                else if (j < 0)
                {
                    j++;
                    move = -move; 
                }
                else if (i < 0)
                {
                    i++;
                    move = -move;
                }
            }
            return nums;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.