已解答
中等
相关标签
相关企业
提示
给你一个
m
行n
列的矩阵matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出:[1,2,3,4,8,12,11,10,9,5,6,7]
题解一:模拟
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
//该返回的列表
List<Integer> order = new ArrayList<Integer>();
//如果二维数组为空或者长度为零,则直接退出不处理
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return order;
}
//rows记录y轴长度,colums记录x轴长度
int rows = matrix.length,columns = matrix[0].length;
//boolean二维数组,判断该元素是否被访问
boolean[][] visited = new boolean[rows][columns];
int total = rows * columns;
//初始下标
int row = 0,column = 0;
//向量数组
int [][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
int directionIndex = 0;
//该循环的次数
for(int i = 0; i < total; i++){
//添加元素
order.add(matrix[row][column]);
//记录,已经被访问过
visited[row][column] = true;
//下一个行索引
int nextRow = row + directions[directionIndex][0];
//下一个列索引
int nextColumn = column + directions[directionIndex][1];
//如果走到边界了,则开始刷新方向
if(nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]){
directionIndex = (directionIndex + 1) % 4;
}
//更新下一级索引
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
}
题解二:遍历
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
//需要返回的List列表
List<Integer> order = new ArrayList<Integer>();
//判断条件
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return order;
}
//行高列宽
int rows = matrix.length,columns = matrix[0].length;
//四个索引
int left = 0,right = columns - 1,top = 0,bottom = rows - 1;
while(left <= right && top <= bottom){
//开始最上层遍历
for(int column = left; column <= right; column++){
order.add(matrix[top][column]);
}
//开始遍历右边
for(int row = top + 1; row <= bottom; row++){
order.add(matrix[row][right]);
}
//假如还有元素
if(left < right && top < bottom){
for(int column = right - 1; column > left; column--){
order.add(matrix[bottom][column]);
}
for(int row = bottom; row > top; row--){
order.add(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
}