Home (Python)(백준_2589) 보물섬
Post
Cancel

(Python)(백준_2589) 보물섬

2589번: 보물섬

BFS를 이용한 풀이


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
from collections import deque

def main():
    rowSize, columnSize = map(int, input().split())

    graph = [ list(input()) for _ in range(rowSize) ]

    result=0
    for x in range(rowSize):
        for y in range(columnSize):
            if graph[x][y]=='L':
                result = max(result, bfs(x, y, graph, rowSize, columnSize))
    print(result)

def bfs(x, y, graph, rowSize, columnSize):
    dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
    queue=deque()
    queue.append((x,y))

    visited = [ [0] * columnSize for _ in range(rowSize) ]
    visited[x][y] = 1

    cnt = 0
    while queue:
        x, y = queue.popleft()

        for i in range(len(dx)):
            nx, ny = x + dx[i], y + dy[i]

            if 0 <= nx < rowSize and 0 <= ny < columnSize and graph[nx][ny] == 'L' and visited[nx][ny] == 0:
                visited[nx][ny] = visited[x][y] + 1
                cnt = max(cnt, visited[nx][ny])
                queue.append([nx, ny])
    return cnt-1

if __name__== "__main__":
    main()
This post is licensed under CC BY 4.0 by the author.