DFS on Matrix
Intuition\n Describe your first thoughts on how to solve this problem. \nConvert the grid to matrix, then run DFS to find how many regions there are\n\n# Approa
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nConvert the grid to matrix, then run DFS to find how many regions there are\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- create matrix of size `grid.length * 3`\n- fill 1s and 0s to the matrix\n- run DFS to find the [number of island](https://leetcode.com/problems/number-of-islands/description/)\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunction regionsBySlashes(grid: string[]): number {\n  const matrix = Array.from({ length: grid.length * 3 }, () => Array(grid[0].length * 3))\n\n  const mapChar = {\n    " ": [\n      [0, 0, 0],\n      [0, 0, 0],\n      [0, 0, 0],\n    ],\n    "/": [\n      [0, 0, 1],\n      [0, 1, 0],\n      [1, 0, 0],\n    ],\n    "\\\\": [\n      [1, 0, 0],\n      [0, 1, 0],\n      [0, 0, 1],\n    ],\n  }\n\n  for (let i = 0; i < grid.length; i++) {\n    for (let j = 0; j < grid[0].length; j++) {\n      const seq = mapChar[grid[i][j]]\n      for (let k = 0; k < 3; k++) {\n        for (let l = 0; l < 3; l++) {\n          matrix[i * 3 + k][j * 3 + l] = seq[k][l]\n        }\n      }\n    }\n  }\n\n  let count = 0\n\n  const DIRECTIONS = [\n    [0, 1], [1, 0], [0, -1], [-1, 0]\n  ]\n  const dfs = (i: number, j: number): boolean => {\n    if (matrix[i][j] !== 0) return false\n    matrix[i][j] = -1\n    for (const [dy, dx] of DIRECTIONS) {\n      const newRow = i + dy\n      const newCol = j + dx\n      if (\n        newRow < 0\n        || newCol < 0\n        || newRow === matrix.length\n        || newCol === matrix[0].length\n        || matrix[newRow][newCol] !== 0) {\n        continue\n      }\n      dfs(newRow, newCol)\n    }\n    return true\n  }\n\n  for (let i = 0; i < matrix.length; i++) {\n    for (let j = 0; j < matrix[0].length; j++) {\n      if (dfs(i, j)) count++\n    }\n  }\n  return count\n}\n\n```
['Depth-First Search', 'Matrix', 'TypeScript', 'JavaScript']