Java simple sol


  • 0
    S
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] result = new int[n][n];
            if (n <= 0) {
                return result;
            }
            for (int i = 0, j = 0, dx = 0, dy = 1, num = 1;
                 num <= n * n; num++, i += dx, j += dy) {
                if (i >= 0 && i < n && j >= 0 && j < n && result[i][j] == 0) {
                    result[i][j] = num;
                } else {
                    // back off
                    i -= dx;
                    j -= dy;
                    num--;
                    // update direction
                    int new_dx = dx == 0 ? -dy : 0;
                    int new_dy = dy == 0 ?  dx : 0;
                    dx = new_dx;
                    dy = new_dy;
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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