原题网址: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
,
[ [ 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[n][n];
spiral(matrix, 1, 0, 0, n-1, n-1);
return matrix;
}
}