Spiral Matrix II

Problem:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
Analysis:
Spiral matrix的马甲。
Solution:

class Solution {
    public int[][] generateMatrix(int n) {
        
        int m = n;
        int[][] matrix = new int[m][n];
        int[] dx = new int[]{0, 1, 0, -1};
        int[] dy = new int[]{1, 0, -1, 0};
        boolean[][] visited =  new boolean[m][n];
        int x = 0, y = 0;
        int d = 0;
        for (int i = 1; i <= n*n; i++) {
             matrix[x][y] = i;
             visited[x][y] = true;
            
             int newx = x + dx[d];
             int newy = y + dy[d];
             if (0 <= newx && newx < m && 0 <= newy && newy < n && !visited[newx][newy]) {
                x = newx;
                y = newy;
             } else {
                d = (d + 1) % 4;
                x += dx[d];
                y += dy[d];
             }
        }
        
        return matrix;
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array