Last active
August 10, 2020 12:21
-
-
Save ShubhamKJha/1038a5962666385b5a983c94e62f6e99 to your computer and use it in GitHub Desktop.
The Rainy Season
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
The solution for Hackerearth problem: The Rainy Season. | |
https://www.hackerearth.com/problem/algorithm/bfs-waali-7409c2ca-c1be890b/description/ | |
The problem is not hard, but due to the limitation of recursion limit | |
in Python, we sometimes need to make different approaches. | |
Here, I've tried an iterative approach. | |
''' | |
# Write your code here | |
from collections import deque | |
m, n = map(int, input().split()) | |
data = [] | |
for _ in range(m): | |
data.append(list(input())) | |
def find_volume(i, j): | |
dq = deque() | |
dq.append((i, j)) | |
res = 0 | |
while(dq): | |
x, y = dq.pop() | |
if x < 0 or y < 0 or x >= m or y >= n: | |
# Water will flow-out | |
res += float('inf') | |
elif data[x][y] != '*': | |
# The cell is not a tower | |
data[x][y] = '*' # make it visited | |
dq.append((x,y+1)) | |
dq.append((x,y-1)) | |
dq.append((x+1,y)) | |
dq.append((x-1,y)) | |
res += 1 | |
return res if res != float('inf') else 0 | |
total_volume = 0 | |
for i in range(m): | |
for j in range(n): | |
if(data[i][j] == '*'): continue | |
total_volume += find_volume(i, j) | |
print(total_volume) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Write your code here | |
m, n = map(int, input().split()) | |
data = [] | |
for _ in range(m): | |
data.append(list(input())) | |
def find_volume(i, j): | |
if i < 0 or j < 0 or i >= m or y >= n: | |
return float('inf') | |
res = 0 | |
if data[i][j] == '*': | |
data[i][j] = '*' | |
res += find_volume((i, j+1)) | |
res += find_volume((i, j-1)) | |
res += find_volume((i+1, j)) | |
res += find_volume((i-1, j)) | |
return res | |
total_volume = 0 | |
for i in range(m): | |
for j in range(n): | |
if(data[i][j] == '*'): continue | |
curr_volume = find_volume(i, j) | |
total_volume += (curr_volume if curr_volume != float('inf') else 0) | |
print(total_volume) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment