LeetCode: Spiral Matrix II Solution

Same with I, with a small modification

Approach

Traverse the empty matrix and assign values

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 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 = 111
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      return29    }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 res42}```

Original problem

Similar problems

Spiral Matrix

Spiral Matrix III

Spiral Matrix IV

leetcode

array

matrix

recursion

Next Post

LeetCode: Delete the Middle Node of a Linked List

Sep 21, 2022

Fast and slow

Search Posts