题目传送地址: https://leetcode.cn/problems/spiral-matrix-ii/
运行效率:

代码如下:
class Solution {
public static int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int count = 1;
String coordinate = "0:0:0";
while (count <= Math.pow(n, 2)) {
String[] split = coordinate.split(":");
Integer row = Integer.parseInt(split[0]);
Integer col = Integer.parseInt(split[1]);
matrix[row][col] = count;
coordinate = getNextCoordinate(coordinate, matrix);
count++;
}
return matrix;
}
/**
* 获取下一个坐标的位置
*
* @param coordinate 当前坐标所在的行 当前坐标所在的列 当前坐标前进的方向
* @param matrix
* @return
*/
public static String getNextCoordinate(String coordinate, int[][] matrix) {
String[] split = coordinate.split(":");
Integer row = Integer.parseInt(split[0]);
Integer col = Integer.parseInt(split[1]);
Integer direction = Integer.parseInt(split[2]);
//从左往右
if (direction == 0) {
//如果右边还有可移动的地方
if (col + 1 <= matrix[0].length - 1 && matrix[row][col + 1] == 0) {
col++;
} else {
direction = 1; // 把坐标前进的方向改为从上到下
row++; //列坐标不变,行坐标下移
}
return row + ":" + col + ":" + direction;
}
//从上往下
if (direction == 1) {
//如果下边还有可移动的地方
if (row + 1 <= matrix.length - 1 && matrix[row + 1][col] == 0) {
row++;
} else {
direction = 2; // 把坐标前进的方向改为从右往左
col--; //行坐标不变,列坐标左移
}
return row + ":" + col + ":" + direction;
}
//从右往左
if (direction == 2) {
//如果左边还有可移动的地方
if (col - 1 >= 0 && matrix[row][col - 1] == 0) {
col--;
} else {
direction = 3; // 把坐标前进的方向改为从下往上
row--; //列坐标不变,行坐标上移
}
return row + ":" + col + ":" + direction;
}
//从下往上
if (direction == 3) {
//如果上边还有可移动的地方
if (row - 1 >= 0 && matrix[row - 1][col] == 0) {
row--;
} else {
direction = 0; // 把坐标前进的方向改为从左往右
col++; //行坐标不变,列坐标右移
}
return row + ":" + col + ":" + direction;
}
return row + ":" + col + ":" + direction;
}
}
















