题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param matrix int整型二维数组
* @return int整型一维数组
*/
export function printMatrix(matrix: number[][]): number[] {
// write code here
//边界模拟法
const res = []
if(matrix.length === 0)return res
//定义四个边界
let left = 0
let right = matrix[0].length - 1
let up = 0
let down = matrix.length - 1
while(left <= right&&up <= down){
//上边界的从左向右打印
for(let i = left;i <= right;i++){
res.push(matrix[up][i])
}
up++
//上边界到下边界
if(up > down){
break
}
for(let i = up;i <= down;i++){
res.push(matrix[i][right])
}
//下边界向上
right--
if(left > right){
break
}
//下边界从右到做
for(let i = right;i >= left;i--){
res.push(matrix[down][i])
}
down--
if(up > down){
break
}
for(let i = down;i >= up;i--){
res.push(matrix[i][left])
}
left++
if(left > right){
break;
}
}
return res
}


