码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Spiral Matrix II

时间:2014-11-17 06:53:48      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   for   div   

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

标签:style   blog   io   color   ar   os   sp   for   div   

原文地址:http://www.cnblogs.com/lishiblog/p/4102806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!