Leetcode 59. Spiral Matrix II

来源:互联网 发布:淘宝做图片视频教程 编辑:程序博客网 时间:2024/05/21 03:16
public class Solution {    public int[][] generateMatrix(int n) {        int[][] res = new int[n][n];        int up = 0, right = n-1, down = n-1, left = 0, elem = 1;                while (true) {            for (int col=left; col<=right; col++) res[up][col] = elem++;            if (++up > down) break;                        for (int row=up; row<=down; row++) res[row][right] = elem++;            if (--right < left) break;                        for (int col=right; col>=left; col--) res[down][col] = elem++;            if (--down < up) break;                        for (int row=down; row>=up; row--) res[row][left] = elem++;            if (++left > right) break;        }                return res;    }}

0 0
原创粉丝点击