首页 > 其他 > 详细

59. Spiral Matrix II

时间:2017-10-11 14:50:24      阅读:254      评论:0      收藏:0      [点我收藏+]

螺旋矩阵

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

原文:http://www.cnblogs.com/fcyworld/p/7650374.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!