LeetCode: Spiral Matrix Solution
Writing recursive function is funApproach
Recursively go with the order of Right - Down - Left - Up
Implementation
1var spiralOrder = function (matrix) {2 const [m, n] = [matrix.length, matrix[0].length]3 const visited = Array.from({ length: m }, _ => Array(n).fill(false))4 const res = []5 const DIR = {6 R: 0,7 D: 1,8 L: 2,9 U: 3,10 }1112 const isValidCell = (i, j) =>13 0 <= i && i < m && 0 <= j && j < n && !visited[i][j]1415 const recursion = (i, j, dir) => {16 if (!isValidCell(i, j)) {17 dir === DIR.R &&18 isValidCell(i + 1, j - 1) &&19 recursion(i + 1, j - 1, DIR.D)20 dir === DIR.D &&21 isValidCell(i - 1, j - 1) &&22 recursion(i - 1, j - 1, DIR.L)23 dir === DIR.L &&24 isValidCell(i - 1, j + 1) &&25 recursion(i - 1, j + 1, DIR.U)26 dir === DIR.U &&27 isValidCell(i + 1, j + 1) &&28 recursion(i + 1, j + 1, DIR.R)29 return30 }3132 res.push(matrix[i][j])33 visited[i][j] = true3435 dir === DIR.R && recursion(i, j + 1, dir)36 dir === DIR.D && recursion(i + 1, j, dir)37 dir === DIR.L && recursion(i, j - 1, dir)38 dir === DIR.U && recursion(i - 1, j, dir)39 }4041 recursion(0, 0, DIR.R)4243 return res44}
References
Similar problems
Spiral Matrix III
Spiral Matrix IV
Comments
Loading comments...
Tags
leetcode
array
matrix
recursion
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Where Will the Ball Fall
If I remember correctly, Alex K. also loves recursion
Previous Post
LeetCode: Happy Number
Use a Set to detect cycle