Simple java solution with sigle while loop


#1
public class Solution {
    public int[][] generateMatrix(int n) {
        int[] row = {0,1,0,-1};
        int[] col = {1,0,-1,0};
        int dir, r, c;
        dir = r = c = 0;
        int val = 1;
        int nxn = n*n;
        int[][] result = new int[n][n];
        
        while(val <= nxn){
            result[r][c] = val++;
            if(changeDir(result, row, col, r, c, dir, n)){
                dir = (dir + 1)%4;
            }
            
            r = r + row[dir];
            c = c + col[dir];
        }
        
        return result;
    }
    
    public boolean changeDir(int[][] result, int[] row, int[] col,
    int r, int c, int dir, int n){
        return r + row[dir] >= n
            || r + row[dir] < 0
            || c + col[dir] >= n
            || c + col[dir] < 0
            || result[r+row[dir]][c+col[dir]] != 0;
    }
}