59. Spiral Matrix II
Posted wilderness
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了59. 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 ] ]
思路:
重复项为一圈一圈的数值
java:
1 class Solution { 2 public int[][] generateMatrix(int n) { 3 int[][] res = new int[n][n]; 4 if(n==0) return res; 5 int row_start = 0, row_end = n-1; 6 int col_start = 0, col_end = n-1; 7 int count = 1; 8 9 while(row_start<=row_end&&col_start<=col_end){ 10 11 for(int i=col_start;i<=col_end;i++){ 12 res[row_start][i] = count++; 13 } 14 row_start++; 15 16 for(int i=row_start;i<=row_end;i++){ 17 res[i][col_end] = count++; 18 } 19 col_end--; 20 21 for(int i=col_end;i>=col_start;i--){ 22 if(row_start<=row_end) 23 res[row_end][i] = count++; 24 } 25 row_end--; 26 27 for(int i=row_end;i>=row_start;i--){ 28 if(col_start<=col_end) 29 res[i][col_start] = count++; 30 } 31 col_start++; 32 33 } 34 return res; 35 } 36 }
以上是关于59. Spiral Matrix II的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 59. Spiral Matrix II
java 59. Spiral Matrix II.java
java 59. Spiral Matrix II.java
java 59. Spiral Matrix II.java