Algorithm Problems

[백준] [Python] 2178번 미로 탐색 - BFS

WakaraNai 2021. 4. 26. 23:58
728x90
반응형

www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

Python

import sys

row, col = map(int, sys.stdin.readline().split())    
board =[ list(map(int, list(sys.stdin.readline().rstrip()))) for _ in range(row) ]

dx = [0,0,1,-1]
dy = [1,-1,0,0]
visit = [[0 for _ in range(col)] for _ in range(row)]
q = []
cnt = 0
for a in range(row):
    for b in range(col):
        if board[a][b] == 1 and visit[a][b] == 0:
            visit[a][b] = 1
            q.append((a,b))
        
            temp_area = 1
            while (len(q) != 0):
                #print(q)
                pos = q.pop(0)
            
                for i in range(4):
                    nx = pos[0] + dx[i]
                    ny = pos[1] + dy[i]
                    if (0<=nx<row and 0<=ny<col):
                        if (visit[nx][ny] == 0 and board[nx][ny] == 1):
                            visit[nx][ny] = visit[pos[0]][pos[1]]+1
                          
                            if nx==row-1 and ny==col-1:
                                cnt = max(cnt,visit[nx][ny])
                            q.append((nx,ny))

print(cnt)

728x90
반응형