Skip to content

Commit 3920ee2

Browse files
author
Chris Wu
committed
no message
1 parent 67e86e5 commit 3920ee2

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

problems/egions-cut-by-slashes.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution(object):
2+
def regionsBySlashes(self, grid):
3+
region = 1
4+
dsu = DSU()
5+
N = len(grid)
6+
7+
#Union the border lines
8+
for i in xrange(N):
9+
dsu.union((i, 0), (i+1, 0))
10+
dsu.union((i, N), (i+1, N))
11+
for j in xrange(N):
12+
dsu.union((0, j), (0, j+1))
13+
dsu.union((N, j), (N, j+1))
14+
15+
#Iterate through slashes and connect the dots
16+
#If the slash connects two already connected dots, the region will increament by one
17+
for i, row in enumerate(grid):
18+
for j, slash in enumerate(row):
19+
if slash=='/':
20+
if not dsu.union((j+1, i), (j, i+1)):
21+
region += 1
22+
elif slash=='\\':
23+
if not dsu.union((j, i), (j+1, i+1)):
24+
region += 1
25+
return region
26+
27+
class DSU(object):
28+
def __init__(self):
29+
self.parant = {}
30+
31+
def find(self, x):
32+
if x not in self.parant:
33+
self.parant[x] = x
34+
35+
if self.parant[x]!=x:
36+
self.parant[x] = self.find(self.parant[x])
37+
38+
return self.parant[x]
39+
40+
def union(self, x, y):
41+
xr, yr = self.find(x), self.find(y)
42+
if xr==yr: return False
43+
self.parant[yr] = xr
44+
return True

0 commit comments

Comments
 (0)