Skip to content

Commit 0d7f8b0

Browse files
committed
feat: python solution, DFS
1 parent 775f8c6 commit 0d7f8b0

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

problems/kamacoder/0103.水流问题.md

+56
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,62 @@ public class Main {
355355
```
356356

357357
### Python
358+
```Python
359+
first = set()
360+
second = set()
361+
directions = [[-1, 0], [0, 1], [1, 0], [0, -1]]
362+
363+
def dfs(i, j, graph, visited, side):
364+
if visited[i][j]:
365+
return
366+
367+
visited[i][j] = True
368+
side.add((i, j))
369+
370+
for x, y in directions:
371+
new_x = i + x
372+
new_y = j + y
373+
if (
374+
0 <= new_x < len(graph)
375+
and 0 <= new_y < len(graph[0])
376+
and int(graph[new_x][new_y]) >= int(graph[i][j])
377+
):
378+
dfs(new_x, new_y, graph, visited, side)
379+
380+
def main():
381+
global first
382+
global second
383+
384+
N, M = map(int, input().strip().split())
385+
graph = []
386+
for _ in range(N):
387+
row = input().strip().split()
388+
graph.append(row)
389+
390+
# 是否可到达第一边界
391+
visited = [[False] * M for _ in range(N)]
392+
for i in range(M):
393+
dfs(0, i, graph, visited, first)
394+
for i in range(N):
395+
dfs(i, 0, graph, visited, first)
396+
397+
# 是否可到达第二边界
398+
visited = [[False] * M for _ in range(N)]
399+
for i in range(M):
400+
dfs(N - 1, i, graph, visited, second)
401+
for i in range(N):
402+
dfs(i, M - 1, graph, visited, second)
403+
404+
# 可到达第一边界和第二边界
405+
res = first & second
406+
407+
for x, y in res:
408+
print(f"{x} {y}")
409+
410+
411+
if __name__ == "__main__":
412+
main()
413+
```
358414

359415
### Go
360416

0 commit comments

Comments
 (0)