Leetcode59 Spiral Matrix II
Posted xuweimdm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode59 Spiral Matrix II相关的知识,希望对你有一定的参考价值。
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 ] ]
Solution1
public class Solution
public int[][] generateMatrix(int n)
int[][] result = new int[n][n];
for(int i=0,k=1;i<(n+1)/2;i++)
for(int j=i;j<n-i;j++) result[i][j] = k++;
for(int j=i+1;j<n-i;j++) result[j][n-i-1] = k++;
for(int j=n-i-2;j>=i;j--) result[n-i-1][j] = k++;
for(int j=n-i-2;j>i;j--) result[j][i] = k++;
return result;
Solution2
public class Solution
public int[][] generateMatrix(int n)
int[][] result = new int[n][n];
int left=0,right=n-1,top=0,down=n-1,k=1;
for(;left<=right;left++)
for(int i=left;i<=right;i++) result[top][i] = k++;
for(int i=++top;i<=down;i++) result[i][right] = k++;
for(int i=--right;i>=left;i--) result[down][i] = k++;
for(int i=--down;i>=top;i--) result[i][left] = k++;
return result;
以上是关于Leetcode59 Spiral Matrix II的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]59. Spiral Matrix II