This is the 24th day of my participation in the August More Text Challenge

preface

The helical matrix is a very interesting problem, and the helical matrix is just taking the terms out of a two-dimensional array, and there’s really no specific algorithm for solving the helical matrix, but you just have to think about the four boundaries: right, down, left, up. Now what’s the problem

Topic describes

You are given a matrix matrix with m rows and n columns. Please return all elements in the matrix in clockwise spiral order. Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]

Output:,2,3,6,9,8,7,4,5 [1]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]

Output:,2,3,4,8,12,11,10,9,5,6,7 [1]

Their thinking

  • The core of this problem is to consider the four margins, and then iterate through a two-dimensional array
  • Define direction to indicate which direction you’re traversing in
  • Define left, right, bottom, and top respectively, changing the direction value and the corresponding left, right, top, bottom after each loop
  • When you go to the right, top stays the same, when you go down, right stays the same, when you go to the left, bottom stays the same, and when you go up, left stays the same, which is very important
  • So if you look at the boundary problem, and you want to take the equals case, let’s do the code
/ * * *@param {number[][]} matrix
 * @return {number[]}* /
var spiralOrder = function(matrix) {
    if(matrix.length === 0) {// Check whether the input is an empty array
        return[]}// Define four directions: right, down, left, and up
    let top = 0
    let bottom = matrix.length-1
    let left = 0
    let right = matrix[0].length-1
    let direction = 'right' 
    let result = []
    while(left<=right && top<=bottom){ // If left is less than right and up is less than down, keep going
        if(direction==='right') {for(leti=left; i<=right; i++){ result.push(matrix[top][i])// Top does not change when you go to the right
            }
            top++
            direction='down'
        }else if(direction==='down') {for(leti=top; i<=bottom; i++){ result.push(matrix[i][right])// Right is the same as right
            }
            right--
            direction = 'left'
        }else if(direction==='left') {for(leti=right; i>=left; i--){ result.push(matrix[bottom][i])// Bottom stays the same when you go to the right
            }
            bottom--
            direction='top'
        }else if(direction==='top') {for(leti=bottom; i>=top; i--){ result.push(matrix[i][left])// Left is the same as left
            }
            left++
            direction='right'}}return result
};
Copy the code

LeetCode runs as follows

conclusion

Gogogo = gogogo = gogogo = gogogo = gogogo = gogogo