Skip to content

Commit 6477517

Browse files
authored
Create 959-regions-cut-by-slashes.js
1 parent d870f55 commit 6477517

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

959-regions-cut-by-slashes.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @param {string[]} grid
3+
* @return {number}
4+
*/
5+
const regionsBySlashes = function(grid) {
6+
const len = grid.length
7+
let regionsNum = 0
8+
const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]
9+
const matrix = Array.from({ length: 3 * len }, () => new Array(3 * len).fill(0))
10+
11+
// 把每个格子切成3 * 3个小格子,再标记出现线段的位置
12+
for (let i = 0; i < len; i++) {
13+
for (let j = 0; j < len; j++) {
14+
if (grid[i][j] === '/') matrix[i * 3][j * 3 + 2] = matrix[i * 3 + 1][j * 3 + 1] = matrix[i * 3 + 2][j * 3] = 1
15+
if (grid[i][j] === '\\') matrix[i * 3][j * 3] = matrix[i * 3 + 1][j * 3 + 1] = matrix[i * 3 + 2][j * 3 + 2] = 1
16+
}
17+
}
18+
19+
for (let i = 0; i < matrix.length; i++) {
20+
for (let j = 0; j < matrix.length; j++) {
21+
if (matrix[i][j] === 0) {
22+
dfs(matrix, i, j, dirs)
23+
regionsNum++
24+
}
25+
}
26+
}
27+
return regionsNum
28+
}
29+
function dfs(m, i, j, dirs) {
30+
if (i >= 0 && j >= 0 && i < m.length && j < m.length && m[i][j] === 0) {
31+
m[i][j] = 1
32+
for (let dir of dirs) dfs(m, i + dir[0], j + dir[1], dirs)
33+
}
34+
}

0 commit comments

Comments
 (0)