Skip to content

Commit 2b3862f

Browse files
Merge pull request #22 from theforestvn88/august
0959
2 parents cf93681 + b2badee commit 2b3862f

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# @param {String[]} grid
2+
# @return {Integer}
3+
def regions_by_slashes(grid)
4+
size = grid.length
5+
# map each slash to three '1' squares, others are '0'
6+
# 0 0 1 0 0
7+
# 0 1 0 1 0
8+
# 1 0 0 0 1
9+
# 0 1 0 1 0
10+
# 0 0 1 0 0
11+
#
12+
# oserved that a region is some connected '0' separeting by '1'
13+
# so we could count number of regions by counting regions of connected '0'
14+
#
15+
# Note: why split slash into 3, not 2
16+
# consider this: ["//", "//"]
17+
# 2 3
18+
# 0 1 1 | 0 0 1 0 1
19+
# 1 1 1 | 0 1 0 1 0
20+
# 1 1 0 | 1 0 1 0 1
21+
# | 0 1 0 1 0
22+
# | 1 0 1 0 0
23+
# as you can see, the right map is correct, there're 4 regions
24+
map = Array.new(size * 3) { Array.new(size * 3, 0) }
25+
26+
i = 0
27+
while i < size
28+
j = 0
29+
while j < size
30+
if grid[i][j] == '/'
31+
map[i*3][j*3+2] = 1
32+
map[i*3+1][j*3+1] = 1
33+
map[i*3+2][j*3] = 1
34+
elsif grid[i][j] == '\\'
35+
map[i*3][j*3] = 1
36+
map[i*3+1][j*3+1] = 1
37+
map[i*3+2][j*3+2] = 1
38+
end
39+
j += 1
40+
end
41+
i += 1
42+
end
43+
44+
# depth-first-search to map all connected '0' squares together and count as a region
45+
dfs = lambda { |i, j|
46+
return if i < 0 || i >= map.size || j < 0 || j >= map.size
47+
return if map[i][j] > 0
48+
49+
map[i][j] = 1
50+
51+
dfs.call(i+1, j)
52+
dfs.call(i-1, j)
53+
dfs.call(i, j+1)
54+
dfs.call(i, j-1)
55+
}
56+
57+
count = 0
58+
(0...map.size).each { |i|
59+
(0...map.size).each { |j|
60+
if map[i][j] == 0
61+
dfs.call(i, j)
62+
count += 1
63+
end
64+
}
65+
}
66+
67+
count
68+
end

0 commit comments

Comments
 (0)