59. Spiral Matrix II

来源:互联网 发布:球员数据对比 编辑:程序博客网 时间:2024/05/02 02:01

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

Subscribe to see which companies asked this question

public class Solution {        public int[][] generateMatrix(int n) {        int [][] ret = new int [n][n];        int i = 1;        int dir = 1;        int x = 0 ;        int y = 0 ;        int lim = n*n;        while(i<=lim){            switch(dir%4)            {                case 1:                    ret[x][y]=i;                    if(y<n-1&&ret[x][y+1]==0)y++;                    else{                        x++;                        dir++;                                            }i++;                    break;                case 2:                    ret[x][y]=i;                    if(x<n-1&&ret[x+1][y]==0)x++;                    else{                      y--;                      dir++;                                          }i++;                    break;                case 3:                    ret[x][y]=i;                    if(y>0&&ret[x][y-1]==0)y--;                    else{                        x--;                        dir++;                    }i++;                    break;                case 0:                    ret[x][y]=i;                    if(ret[x-1][y]==0)x--;                    else{                        y++;                        dir++;                    }i++;                    break;                default:break;                }        }        return ret;    }}

0 0
原创粉丝点击