59. Spiral Matrix II java solutions

Posted Miller1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了59. Spiral Matrix II java solutions相关的知识,希望对你有一定的参考价值。

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 ]
]
 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         int startx = 0,starty = 0,endx = n-1,endy = n-1;
 4         int[][] ans = new int[n][n];
 5         int count = 1;
 6         while(startx <= endx && starty <= endy){
 7             for(int i = startx;i<=endx;i++){
 8                 ans[starty][i] = count++;
 9             }
10             starty++;
11             
12             for(int i = starty;i<=endy;i++){
13                 ans[i][endx] = count++;
14             }
15             endx--;
16             
17             for(int i = endx;i>=startx;i--){
18                 ans[endy][i] = count++;
19             }
20             endy--;
21             
22             for(int i = endy;i>=starty;i--){
23                 ans[i][startx] = count++;
24             }
25             startx++;
26         }
27         return ans;
28     }
29 }

模拟螺旋打印的过程即可。

以上是关于59. Spiral Matrix II java solutions的主要内容,如果未能解决你的问题,请参考以下文章

java 59. Spiral Matrix II.java

java 59. Spiral Matrix II.java

java 59. Spiral Matrix II.java

java 59. Spiral Matrix II.java

59. Spiral Matrix II java solutions

leetcode 59 Spiral Matrix II ------ java