Very simple and short Java Solution


  • 0
    M
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[] dr = new int[]{0, 1, 0, -1};
            int[] dc = new int[]{1, 0, -1, 0};
            int[][] ans = new int[n][n];
            if(n == 0) return ans;
            int count = 1, mov = 0, i = 0, j = -1;
            for(int k = 0; k/n < n; k++) {
                i += dr[mov];
                j += dc[mov];
                ans[i][j] = count++;
                if(i + dr[mov] < 0 || i + dr[mov] == n 
                    || j + dc[mov] < 0 || j + dc[mov] == n || ans[i + dr[mov]][j + dc[mov]] != 0) mov = (mov+1)%4;
            }
            
            return ans;
        }
    }
    

Log in to reply
 

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