js 面试题 顺时针打印矩阵

在这里插入图片描述
思路是:先往右走,然后top++(则往下一层),再往下走 ,right–,往左走,bottom–,往上走 left++结合图片会更容易理解

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
 var spiralOrder = function(matrix) {
     if(matrix.length==0){
         return []
     }
    var result=[]
    let top=0
    let right=matrix[0].length-1
    let bottom=matrix.length-1
    let left=0
    while(true){
        for(var l=left;l<=right;l++){
            result.push(matrix[top][l])
        }
        top++;
        if(top>bottom){
            break
        }
        console.log(top)
        for(var t=top;t<=bottom;t++){
            console.log(matrix[t][right])
            result.push(matrix[t][right])
        }
        right--;
        if(left>right){
            break
        }
        for(var r=right;r>=left;r--){
            result.push(matrix[bottom][r])
        }
        bottom--;
          if(top>bottom){
            break
        }
        for(var b=bottom;b>=top;b--){
            result.push(matrix[b][left])
        }
        left++
         if(left>right){
            break
        }
    }
    return result;
};

猜你喜欢

转载自blog.csdn.net/qq_41988554/article/details/104777714