面试题29. 顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
/**
* @param {number[][]} matrix
* @return {number[]}
*/
/*
// 这种方法有问题,某些特殊测试用例总是会缺失
var spiralOrder = function(matrix) {
if(!matrix.length) return []
let h = matrix.length, w = matrix[0].length;
let res = [];
for(let i=0; i<h/2; i++){
for(let j=i; j<w-i; j++){
res.push(matrix[i][j])
}
for(let m=i+1; m<=h-1-i; m++){
res.push(matrix[m][w-i-1])
}
for(let n=w-i-2; n>=0 && i+1<h-1; n--){
console.log('3: ',matrix[h-i-1][n])
res.push(matrix[h-i-1][n])
}
for(let k=h-i-2; k>=i+1; k--){
console.log('4: ',matrix[k][i])
res.push(matrix[k][i])
}
}
return res
};
*/
var spiralOrder = function(matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return [];
}
let rows = matrix.length, columns = matrix[0].length;
let visited = new Array(rows)
for(let i=0; i<rows; i++){
visited[i] = new Array(columns)
}
let total = rows * columns;
let order = new Array(total);
let row = 0, column = 0;
let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
let directionIndex = 0;
for (let i = 0; i < total; i++) {
order[i] = matrix[row][column];
visited[row][column] = true;
let nextRow = row + directions[directionIndex][0], 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;
}
思考:
let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; 4个方向的题解,不容易出错,好理解,又通用
第一种解法的思路是下面的,控制4个变量往里面缩小距形。
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int rows = matrix.length, columns = matrix[0].length;
int[] order = new int[rows * columns];
int index = 0;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
order[index++] = matrix[top][column];
}
for (int row = top + 1; row <= bottom; row++) {
order[index++] = matrix[row][right];
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
order[index++] = matrix[bottom][column];
}
for (int row = bottom; row > top; row--) {
order[index++] = matrix[row][left];
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。