首页 > 代码库 > Leetcode-Spiral Matrix II
Leetcode-Spiral Matrix II
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 ]]
Have you met this question in a real interview?
Solution:
1 public class Solution { 2 public int[][] generateMatrix(int n) { 3 int[][] matrix = new int[n][n]; 4 5 int[] x = new int[]{0,1,0,-1}; 6 int[] y = new int[]{1,0,-1,0}; 7 int direction = 0; 8 int curX = 0, curY=0; 9 int rowStart = 0, rowEnd = n-1, colStart=0, colEnd=n-1;10 int len = n*n;11 12 for (int i=0;i<len;i++){13 matrix[curX][curY]=i+1; 14 int nextX = curX+x[direction];15 int nextY = curY+y[direction]; 16 //Determin the availability of next point.17 if (nextX>rowEnd || nextX<rowStart || nextY>colEnd || nextY<colStart){18 direction = (direction+1)%4;19 nextX = curX+x[direction];20 nextY = curY+y[direction];21 //Update the availability of rows and cols according the direction change.22 if (direction==1) rowStart++;23 if (direction==2) colEnd--;24 if (direction==3) rowEnd--;25 if (direction==0) colStart++;26 }27 curX = nextX;28 curY = nextY;29 }30 31 return matrix;32 33 }34 }
Leetcode-Spiral Matrix II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。