java 59. Spiral Matrix II.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 59. Spiral Matrix II.java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int[][] generateMatrix(int n) {
        if (n < 1) return new int[0][0];
        int[][] res = new int[n][n];
        int left = 0, right = n - 1, up = 0, down = n - 1;
        int k = 1;
        while(true) {
            for (int i = left; i <= right; i++) {
                res[up][i] = k++;
            }
            if (++up > down) break;
            for (int i = up; i <= down; i++) {
                res[i][right] = k++;
            }
            if(--right < left) break;
            for (int i = right; i >= left; i--) {
                res[down][i] = k++;
            }
            if (--down < up) break;
            for (int i = down; i >= up; i--) {
                res[i][left] = k++;
            }
            if (++left > right) break;
        }
        return res;
    }
}

以上是关于java 59. Spiral Matrix II.java的主要内容,如果未能解决你的问题,请参考以下文章

java 59. Spiral Matrix II.java

java 59. Spiral Matrix II.java

java 59. Spiral Matrix II.java

java 59. Spiral Matrix II.java

59. Spiral Matrix II java solutions

leetcode 59 Spiral Matrix II ------ java