# LeetCode: Spiral Matrix Solution

Writing recursive function is fun

## Approach

Recursively go with the order of Right - Down - Left - Up

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var 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      return30    }31
32    res.push(matrix[i][j])33    visited[i][j] = true34
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 res44}```

Original problem

## Similar problems

Spiral Matrix II

Spiral Matrix III

Spiral Matrix IV

leetcode

array

matrix

recursion

## Next Post

LeetCode: Where Will the Ball Fall

Aug 25, 2022

If I remember correctly, Alex K. also loves recursion

## Previous Post

LeetCode: Happy Number

Aug 24, 2022

Use a Set to detect cycle

Search Posts