Spiral Matrix II

来源:互联网 发布:部落冲突巨人升级数据 编辑:程序博客网 时间:2024/06/11 02:25

Given an integer n, generate a square matrix filled with elements from 1 ton2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]

思路:

这个算法跟之前的 Sprial Matrix I,一模一样。

不一样的地方就是按着递增的加数进去就行了。

public class Solution {    public int[][] generateMatrix(int n) {        int N = Math.abs(n);        int num = 1;        int[][] matrix = new int[N][N];                int beginX = 0; int endX = N-1;        int beginY = 0; int endY = N-1;                while(true){            // left to right;             for(int col=beginY; col<=endY; col++){                 matrix[beginX][col] = num;                 num++;             }             if(++beginX>endX) break;                          //top to bottom;             for(int row = beginX; row<=endX; row++){                 matrix[row][endY] = num;                 num++;             }             if(--endY<beginY) break;                          //right to left;             for(int col = endY; col>=beginY; col--){                 matrix[endX][col]=num;                 num++;             }             if(--endX<beginX) break;                          //bottom to top;             for(int row = endX; row>=beginX; row--){                 matrix[row][beginY]=num;                 num++;             }             if(++beginY>endY) break;        }        return matrix;    }}




0 0