// 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
// 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
// 输出:[1,2,3,6,9,8,7,4,5]
// 时间复杂度:O(mn). 其中 m 和 n 分别是输入矩阵的行数和列数。矩阵中的每个元素都要被访问一次。
// 空间复杂度:O(mn). 需要创建一个大小为 m×n 的矩阵, visited记录每个位置是否被访问过
/*思路:①判断矩阵是否是空的,是否是二维矩阵
②初始化变量:矩阵行、列数,记录是否访问的矩阵,存放结果的一维数组
③初始化方向索引、方向
④遍历:把值传入一维数组、顺时针改变顺序、定义判断条件*/
var result = function(matrix) {
// console.log(matrix.length);
// console.log(matrix[0].length);
if (!matrix.length || !matrix[0].length){ // 前者表示矩阵的行数,后者表示矩阵的列数
// console.log(matrix.length);
return [];
}
const rows = matrix.length, cols = matrix[0].length;
// map之后就能得到二维数组
const visited = new Array(rows).fill(0).map(()=>new Array(cols).fill(false)); //得到一个矩阵,里面值为false
const total = rows*cols;
const order = new Array(total).fill(0); //创建一个一维数组,里面都是0
let directionIndex = 0, row=0, col=0;
const directions = [[0,1], [1,0], [0,-1], [-1,0]]; // 代表四个方向
for (let i=0; i<total; i++){
// console.log(row,col);
order[i] = matrix[row][col]; //给每个一维数组赋二位数组的值
visited[row][col] = true;
// 定义下一个即将访问的二维数组的索引,行和列都是根据direcrion中的数组来相加(而这个相加的要根据方向来)
// directionIndex有四个值,分别为0,1,2,3,这用来选取方向
// nextRow、nextCol先来预判断一下方向
const nextRow = row+directions[directionIndex][0], nextCol = col+directions[directionIndex][1];
//判断条件:若有一个不满足:值超出边界、该值已经访问
// console.log(nextRow,nextCol);
if (!(0<=nextRow && nextRow<rows && 0<=nextCol&&nextCol<cols&&!(visited[nextRow][nextCol]))){
// 如果条件满足就换一个方向
directionIndex = (directionIndex+1)%4; // 这样取余使第五个方向和第一个方向一样
}
row += directions[directionIndex][0];
col += directions[directionIndex][1];
}
return order;
};
console.log(result([[1,2,3],[4,5,6],[7,8,9]]));
版权声明:本文为tinyint_813原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。