LeetCode: Spiral Matrix II Solution

Same with I, with a small modification

Approach

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 }
9
10 let el = 1
11
12 const isValidCell = (i, j) => 0 <= i && i < n && 0 <= j && j < n && !res[i][j]
13
14 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 return
29 }
30
31 res[i][j] = el++
32
33 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 }
38
39 recursion(0, 0, DIR.R)
40
41 return res
42}

References

Original problem

Similar problems

Spiral Matrix

Spiral Matrix III

Spiral Matrix IV

Comments

Loading comments...

Tags

leetcode

array

matrix

recursion

Next Post

LeetCode: Delete the Middle Node of a Linked List

Fast and slow

HoningJS

Search Posts