您的位置:首页 > 其它

LeetCode 59. Spiral Matrix II(螺旋矩阵)

2016-05-21 07:50 387 查看
原题网址:https://leetcode.com/problems/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 ]
]

方法:递归。

public class Solution {
private void spiral(int[][] matrix, int value, int left, int top, int right, int bottom) {
if (left>right || top>bottom) return;
if (left==right && top==bottom) {
matrix[top][left]=value;
return;
}
for(int j=left; j<right; j++) matrix[top][j]=value++;
for(int i=top; i<bottom; i++) matrix[i][right]=value++;
for(int j=right; j>left; j--) matrix[bottom][j]=value++;
for(int i=bottom; i>top; i--) matrix[i][left]=value++;
spiral(matrix, value, left+1, top+1, right-1, bottom-1);
}
public int[][] generateMatrix(int n) {
int[][] matrix = new int

;
spiral(matrix, 1, 0, 0, n-1, n-1);
return matrix;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: