LeetCode: Spiral Matrix Solution

Writing recursive function is fun

Approach

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 }
11
12 const isValidCell = (i, j) =>
13 0 <= i && i < m && 0 <= j && j < n && !visited[i][j]
14
15 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 return
30 }
31
32 res.push(matrix[i][j])
33 visited[i][j] = true
34
35 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 }
40
41 recursion(0, 0, DIR.R)
42
43 return res
44}

References

Original problem

Similar problems

Spiral Matrix II

Spiral Matrix III

Spiral Matrix IV

Comments

Loading comments...

Tags

leetcode

array

matrix

recursion

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

HoningJS

Search Posts