标签:
原题链接在这里:https://leetcode.com/problems/spiral-matrix-ii/
与Spiral Matrix类似。从外圈到内圈螺旋着填数,如果n是奇数的话,最后正中间的数需要单独填写。
AC Java:
1 public class Solution { 2 public int[][] generateMatrix(int n) { 3 int [][] res = new int[n][n]; 4 int x = 0; 5 int y = 0; 6 int row = 0; 7 int column = 0; 8 int num = 1; 9 int temp = n; 10 11 while(row<temp && column<temp){ 12 for(int i = 0; i<temp-1; i++){ 13 res[x][y++] = num++; 14 } 15 for(int i = 0; i<temp-1; i++){ 16 res[x++][y] = num++; 17 } 18 for(int i = 0; i<temp-1; i++){ 19 res[x][y--] = num++; 20 } 21 for(int i = 0; i<temp-1; i++){ 22 res[x--][y] = num++; 23 } 24 x++; 25 y++; 26 temp-=2; 27 } 28 if(n%2 == 1){ 29 res[n/2][n/2] = num; 30 } 31 return res; 32 } 33 }
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4839911.html