Tuesday, March 8, 2022

Leetcode discuss: 498. Diagonal Traverse

 March 8, 2022

Here is the link. 

C# | Automatically direction change

March 7, 2022
Introduction
It is challenge for me to write a working solution to automate direction change using direction array. I came cross a few failed test cases, so I made a few changes on my code.

The following C# code passes online judge.

public class Solution {
    public int[] FindDiagonalOrder(int[][] mat) {
         if (mat == null || mat.Length == 0 || mat[0].Length == 0)
                return new int[0];
            
            var rows = mat.Length;
            var columns = mat[0].Length;            

            // up, -1, down, 1
            var directionRow = new int[] { -1, 1 };
            var directionCol = new int[] { 1, -1 };            

            var startRow = 0;
            var startCol = 0;
            int index = 0;
            int direction = 0;
            var diagonal = new int[rows * columns];

            while (index < rows * columns)
            {
                diagonal[index] = mat[startRow][startCol];
                index++;

                var nextRow = startRow + directionRow[direction];
                var nextCol = startCol + directionCol[direction];

                if (nextRow >= 0 && nextRow < rows && nextCol >= 0 && nextCol < columns)
                {
                    startRow = nextRow;
                    startCol = nextCol;                    
                }
                else
                {   // go up 
                    if (direction == 0)
                    {
                        if (startCol < columns - 1)
                            startCol += 1; // increment column value
                        else
                            startRow += 1;

                    }
                    else
                    {   // go down
                        if (startRow < rows - 1)
                            startRow += 1;
                        else
                            startCol += 1;
                    }

                    direction = (direction + 1) % 2;                    
                }
            }

            return diagonal;
    }
}

No comments:

Post a Comment