[leetcode] 59. 螺旋矩阵 II

59. 螺旋矩阵 II

这题跟54. 螺旋矩阵讨论是一样的

就不废话了

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] dx = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        boolean[][] f = new boolean[n][n];
        int cur = 0;
        int i = 0, j = 0;
        int k = 1;
        int[][] ans = new int[n][n];
        while (k <= n * n) {
            ans[i][j] = k;
            k++;
            f[i][j] = true;
            if (i + dx[cur][0] == n || i + dx[cur][0] < 0
                    || j + dx[cur][1] == n || j + dx[cur][1] < 0
                    || f[i + dx[cur][0]][j + dx[cur][1]]) {
                cur = (cur + 1) % 4;
            }
            i += dx[cur][0];
            j += dx[cur][1];
        }
        return ans;
    }
}
posted @ 2018-07-23 23:37 ACBingo 阅读(...) 评论(...) 编辑 收藏