题目描述:
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
解析:
1.如果数组为空,则返回空数组
2.定义四个边界及当前方向
3.当左边界小于等于右边界,且上边界小于等于下边界时,执行while循环:
按照右、下、左、上的顺序,依次将路径上的字符添加到结果里
4.while循环结束后,返回结果
Java:
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList();
if(matrix.length == 0) {
return result;
}
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
String direction = "right";
while(left <= right && top <= bottom) {
if(direction == "right") {
for(int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
top++;
direction = "down";
} else if(direction == "down") {
for(int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--;
direction = "left";
} else if(direction == "left") {
for(int i = right; i >= left ; i--) {
result.add(matrix[bottom][i]);
}
bottom--;
direction = "top";
} else if(direction == "top") {
for(int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++;
direction = "right";
}
}
return result;
}JavaScript:
var spiralOrder = function(matrix) {
if(matrix.length === 0) {
return [];
}
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
let direction = "right";
let result = [];
while(left <= right && top <= bottom) {
if(direction === "right") {
for(let i = left; i <= right; i++) {
result.push(matrix[top][i]);
}
top++;
direction = "down";
} else if(direction === "down") {
for(let i = top; i <= bottom; i++) {
result.push(matrix[i][right]);
}
right--;
direction = "left";
} else if(direction === "left") {
for(let i = right; i >= left; i--) {
result.push(matrix[bottom][i]);
}
bottom--;
direction = "top";
} else if(direction === "top") {
for(let i = bottom; i >= top; i--) {
result.push(matrix[i][left]);
}
left++;
direction = "right";
}
}
return result;
};
京公网安备 11010502036488号