【LeetCode】 059. Spiral Matrix II

来源:互联网 发布:诊疗指南软件下载 编辑:程序博客网 时间:2024/05/18 21:11

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 ]]

public class Solution {    public int[][] generateMatrix(int n) {        int[][] res = new int[n][n];        if (n == 0) {            return res;        }        int rowStart = 0, rowEnd = n - 1, colStart = 0, colEnd = n - 1, num = 1;        while (rowStart <= rowEnd && colStart <= colEnd) {            for (int i = colStart; i <= colEnd; i++) {                res[rowStart][i] = num++;            }            rowStart++;            for (int i = rowStart; i <= rowEnd; i++) {                res[i][colEnd] = num++;            }            colEnd--;            for (int i = colEnd; i >= colStart; i--) {                res[rowEnd][i] = num++;            }            rowEnd--;            for (int i = rowEnd; i >= rowStart; i--) {                res[i][colStart] = num++;            }            colStart++;        }        return res;    }}


0 0