LeetCode: Spiral Matrix II Solution
Same with I, with a small modificationApproach
Traverse the empty matrix and assign values
Implementation
1var generateMatrix = function (n) {2 const res = Array.from({ length: n }, _ => Array(n).fill(false))3 const DIR = {4 R: 0,5 D: 1,6 L: 2,7 U: 3,8 }910 let el = 11112 const isValidCell = (i, j) => 0 <= i && i < n && 0 <= j && j < n && !res[i][j]1314 const recursion = (i, j, dir) => {15 if (!isValidCell(i, j)) {16 dir === DIR.R &&17 isValidCell(i + 1, j - 1) &&18 recursion(i + 1, j - 1, DIR.D)19 dir === DIR.D &&20 isValidCell(i - 1, j - 1) &&21 recursion(i - 1, j - 1, DIR.L)22 dir === DIR.L &&23 isValidCell(i - 1, j + 1) &&24 recursion(i - 1, j + 1, DIR.U)25 dir === DIR.U &&26 isValidCell(i + 1, j + 1) &&27 recursion(i + 1, j + 1, DIR.R)28 return29 }3031 res[i][j] = el++3233 dir === DIR.R && recursion(i, j + 1, dir)34 dir === DIR.D && recursion(i + 1, j, dir)35 dir === DIR.L && recursion(i, j - 1, dir)36 dir === DIR.U && recursion(i - 1, j, dir)37 }3839 recursion(0, 0, DIR.R)4041 return res42}
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: Delete the Middle Node of a Linked List
Fast and slow