-
Notifications
You must be signed in to change notification settings - Fork 2
/
DFS_connected_cells_in_grid.py
81 lines (55 loc) · 1.54 KB
/
DFS_connected_cells_in_grid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""
Name: DFS: Connected Cell in a Grid
URL: https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid
"""
def get_adjacent_counts(mtrx, i, j, visited):
m = len(mtrx)
n = len(mtrx[0])
count = 1
visited[i * n + j] = 1
from_i = max(i-1, 0)
to_i = min(m-1, i+1)+1
from_j = max(j-1, 0)
to_j = min(n-1, j+1)+1
for ii in range(from_i, to_i):
for jj in range(from_j, to_j):
# already visited
if visited[ii * n + jj] == 1:
continue
# not visited and filled
elif(mtrx[ii][jj] == 1):
count += get_adjacent_counts(mtrx, ii, jj, visited)
# not visited and empty
else:
pass
return count
def get_biggest_region(mtrx):
m = len(mtrx)
n = len(mtrx[0])
maxx = 0
visited = [0 for _ in range(m * n)]
for i in range(m):
for j in range(n):
# already visited or empty
if visited[i * n + j] == 1 or mtrx[i][j] != 1:
continue
# not visited and filled
else:
count = get_adjacent_counts(mtrx,i,j,visited)
if count > maxx:
maxx = count
return maxx
# grid = [
# [0,0,0,1],
# [1,1,0,1],
# [0,1,0,1],
# [1,0,0,0],
# [0,0,1,1]
# ]
n = int(raw_input().strip())
m = int(raw_input().strip())
grid = []
for grid_i in xrange(n):
grid_temp = map(int, raw_input().strip().split(' '))
grid.append(grid_temp)
print get_biggest_region(grid)