首页 > 其他 > 详细

Spiral Matrix II

时间:2014-02-17 16:52:41      阅读:372      评论: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 ]
]
bubuko.com,布布扣
 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         int []count = {1};
 4         int [][] m = new int[n][n];
 5         int start = 0;
 6         while(start<=n/2){
 7             fill(m,start,count);
 8             start++;
 9         }
10         return m;
11     }
12     public void fill(int[][]m,int start,int[]count){
13         int end = m.length-start-1;
14         //up
15         for(int i=start;i<=end;i++){
16             m[start][i] = count[0]++;
17         }
18         //right
19         for(int i=start+1;i<=end;i++){
20             m[i][end] = count[0]++;
21         }
22         //down
23         for(int i=end-1;i>=start;i--){
24             m[end][i] = count[0]++;
25         }
26         //left
27         for(int i=end-1;i>start;i--){
28             m[i][start] = count[0]++;
29         }
30     }
31 }
View Code

Spiral Matrix II

原文:http://www.cnblogs.com/krunning/p/3552038.html

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