Java Very Simple and Straight forward Solution


  • 0
    L

    Just walk through this spiral matrix and fill up the value one by one.

    public int[][] generateMatrix(int n) {
        int[][] ret = new int[n][n];
        int[][] dirs = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
        int len = n, dir_num = 0, num = 1;
        int x = 0, y = -1;
        while(len > 0){
            for(int j = 0; j < len; j++){
                x += dirs[dir_num%4][0];
                y += dirs[dir_num%4][1];
                ret[x][y] = num++;
            }
            dir_num++;
            if((dir_num%2) == 1) len--;
        }
        return ret;   
    }
    

Log in to reply
 

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