给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
难度:中等。(15年吉林大学软件工程考研真题)
算法思路:拿到题的第一反应就是递归求解了,然后就是DFS深度优先搜索,当然有了思路到编码部分还是有点困难的…虽然以前有写过有关DFS的程序,但是不是很熟练,这里稍微改了一下官方题解的DFS,然后打了一些注释好理解一点,其实DFS就像是机器人走迷宫一样的。
源代码:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0) {
return order;
}
int rows = matrix.length;//行数
int columns = matrix[0].length;//列数
//定义一个标记数组,来标记
boolean[][] visited = new boolean[rows][columns];
//机器人总共需要走的步数
int total = rows * columns;
int x = 0, y = 0;//x和y代表机器人当前所在位置
//定义一个代表方向的二维数组,0代表向右走,1代表向左走,2代表向右走,3代表向上走,因为题目要求顺时针
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int directionIndex = 0;
for (int i = 0; i < total; i++) {
order.add(matrix[x][y]);
visited[x][y] = true;//经过这个位置了,将其标记
//下一个位置的坐标
int next_x = x + directions[directionIndex][0], next_y = y + directions[directionIndex][1];
//判断下一个位置是否不满足条件,如果不满足,则将改变方向移动
if (next_x < 0 || next_x >= rows || next_y < 0 || next_y >= columns || visited[next_x][next_y]) {
directionIndex = (directionIndex + 1) % 4;
}
x += directions[directionIndex][0];
y += directions[directionIndex][1];
}
return order;
}
}
执行用时:
0 ms ,在所有 Java 提交中击败了100%的用户
内存消耗:
36.9 MB, 在所有 Java 提交中击败了5.13%的用户