1、题目名称
Spiral Matrix(螺旋输出矩阵中的元素)
2、题目地址
https://leetcode.com/problems/spiral-matrix-ii/
3、题目内容
英文:Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
中文:给出一个整数n,生成一个矩阵,使用数字1到n^2以螺旋顺序填充这个矩阵
例如:给出n=3,则生成如下矩阵:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
4、解题方法1
做这道题的方式可以参考SpiralMatrix,遍历顺序是一样的,只不过SpiralMatrix是取数,这道题要做的是赋值。
Java代码如下:
/**
* @功能说明:LeetCode 59 - Spiral Matrix II
* @开发人员:Tsybius2014
* @开发时间:2015年11月3日
*/
public class Solution {
/**
* 生成矩阵
* @param n
* @return
*/
public int[][] generateMatrix(int n) {
if (n < 0) {
n = 0;
}
int[][] matrix = new int[n][n];
if (n == 0) {
return matrix;
}
int counter = 1;
//左右上下四个边界
int left = 0;
int right = matrix[0].length - 1;
int top = 0;
int bottom = matrix.length - 1;
int i;
while (true) {
//上边,自左至右
for (i = left; i <= right; i++) {
matrix[top][i] = counter++;
}
if (++top > bottom) {
break;
}
//右边,自上至下
for (i = top; i <= bottom; i++) {
matrix[i][right] = counter++;
}
if (left > --right) {
break;
}
//下边,自右至左
for (i = right; i >= left; i--) {
matrix[bottom][i] = counter++;
}
if (top > --bottom) {
break;
}
//左边,自下至上
for (i = bottom; i >= top; i--) {
matrix[i][left] = counter++;
}
if (++left > right) {
break;
}
}
return matrix;
}
}
END