leetCode-Spiral Matrix II

来源:互联网 发布:填表软件 编辑:程序博客网 时间:2024/05/19 17:08

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

Solution:

class Solution {    public int[][] generateMatrix(int n) {        int result[][] = new int[n][n];        int right = n - 1,down  = n - 1;        int x = 0,y = 0;        int count = 1;        while(y <= right){            for(int i = y;i <= right;i++){                result[x][i] = count++;            }            x++;            for(int j = x;j <= down;j++){                result[j][right] = count++;            }            right--;            for(int i = right;i >= y;i--){                result[down][i] = count++;            }            down--;            for(int j = down;j >= x;j--){                result[j][y] = count++;            }            y++;        }        return result;    }}
原创粉丝点击