Simple Java Solution


  • 0
    I
    • Changes direction if the next cell in the path hits the corner
    public class Solution {
        public int[] findDiagonalOrder(int[][] matrix) {
            if (matrix.length == 0) {
                return new int[0];
            }
            int row = matrix.length;
            int column = matrix[0].length;
            int[] result = new int[row * column];
            int x = 0;
            int currRow = 0, currCol = 0;
            boolean up = true; // otherwise, it's down
            while (x != (row * column)) {
                result[x++] = matrix[currRow][currCol];
                if (up) {
                    if (currCol + 1 >= column) {
                        up = false;
                        currRow++;
                    } else if (currRow - 1 < 0) {
                        up = false;
                        currCol++;
                    } else {
                        currRow--;
                        currCol++;
                    }
                } else {
                    if (currRow + 1 >= row) {
                        up = true;
                        currCol++;
                    } else if (currCol - 1 < 0) {
                        up = true;
                        currRow++;
                    } else {
                        currRow++;
                        currCol--;
                    }
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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