js interview questions print matrix clockwise

Insert picture description here
The idea is: first go to the right, then top++ (then go to the next level), then go down, right–, go left, bottom–, go up, left++ and pictures will be easier to understand

/**
 * @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;
};

Guess you like

Origin blog.csdn.net/qq_41988554/article/details/104777714