Share with my java solution


  • 0
    F

    Use simulation such as I

    class Solution {
        public int[][] generateMatrix(int n) {
            int[][] res = new int[n][n];
            
            boolean[][] visited = new boolean[n][n];
            int[] dr = {0, 1, 0, -1};
            int[] dc = {1, 0, -1, 0};
            
            int r = 0, c = 0, id = 0;
            for (int i = 0; i < n * n; i++) {
                res[r][c] = i + 1;
                visited[r][c] = true;
                
                int cr = r + dr[id];
                int cc = c + dc[id];
                
                if (cr >= 0 && cr < n && cc >= 0 && cc < n && !visited[cr][cc]) {
                    r = cr;
                    c = cc;
                } else {
                    id = (id + 1) % 4;
                    r += dr[id];
                    c += dc[id];
                }
            }
            return res;
        }
    }
    
    

Log in to reply
 

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