您的位置:首页 > 其它

59. Spiral Matrix II

2017-07-30 15:17 260 查看

题目

生成螺旋矩阵

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 ]
]


思路

递归实现

code

public class Solution {
private int[,] matrix;
private int elen;
public int[,] GenerateMatrix(int n)
{
matrix = new int[n, n];
elen = 0; //element count
spiral(0, n-1, n-1, 0);
return matrix;
}
private void spiral(int top, int right, int bottom, int left)
{
if (top > bottom || left > right) return;
//add first row
for (int j = left; j <= right; j++)
matrix[top, j] = ++elen;
//add last column
for (int i = top + 1; i <= bottom; i++)
matrix[i, right] = ++elen;
//add last row
for (int j = right - 1; j >= left && top != bottom; j--)
matrix[bottom, j] = ++elen;
//add first column
for (int i = bottom - 1; i > top && left != right; i--)
matrix[i, left] = ++elen;
spiral(top + 1, right - 1, bottom - 1, left + 1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: