Java solution abstracting direction changes into row and column deltas


  • 0
    E
    public int[][] generateMatrix(int n) {
        int[][] m = new int[n][n];
        int[][] deltas = new int[][] {
                    {0, 1},  // move right
                    {1, 0},  // move down
                    {0, -1}, // move left
                    {-1, 0}  // move up
            };
        int counter = 0;
        int r = 0;
        int c = -1; // our first move is right, so start one step beyond
    
        while (counter < n*n) {
            for (int[] delta : deltas) {
                int rd = delta[0]; // row delta
                int cd = delta[1]; // column delta
                
                // continue to move in the same direction until we will hit the border or an occupied element
                while (r+rd < n && c+cd < n && r+rd >= 0 && c+cd >= 0 && m[r+rd][c+cd] == 0) {
                    r += rd;
                    c += cd;
                    m[r][c] = ++counter;
                }
            }
        }
        return m;
    }
    

    Instead of using multiple for-loops, I abstracted the idea of changing direction into delta operations on the row and column.


Log in to reply
 

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