59. Spiral Matrix II

来源:互联网 发布:中国软件排名 编辑:程序博客网 时间:2024/06/11 03:28

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 ]]
解题思路类似于Spiral Matrix I,螺旋遍历,只是这里因为是n*n的矩阵,所以不用做代码中的判断:

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

0 0