본문 바로가기
알고리즘

연구소 14502 BFS

by 토니짱 2022. 9. 18.
from collections import deque
import copy

def bfs():
  visit = copy.deepcopy(graph)
  queue = deque()
  for i in range(n):
    for j in range(m):
      if visit[i][j] == 2:
        queue.append((i,j))

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

    for i in range(4):
      nx = x+dx[i]
      ny = y+dy[i]
      if 0<=nx<n and 0<=ny<m and visit[nx][ny]==0:
        visit[nx][ny]=2
        queue.append((nx,ny))
  global answer
  cnt = 0
  for i in range(n):
    cnt += visit[i].count(0)
  answer = max(cnt,answer)

def dfs_wall(cnt):
  if cnt == 3 :
    bfs()
    return
  
  for i in range(n):
    for j in range(m):
      if graph[i][j] == 0:
        graph[i][j] = 1
        dfs_wall(cnt+1)
        graph[i][j] = 0


n,m = list(map(int, input().split()))
graph=[list(map(int,input().split())) for _ in range(n)]

dx = [-1,1,0,0]
dy = [0,0,-1,1]
  
answer = 0
dfs_wall(0)
print(answer)
반응형

'알고리즘' 카테고리의 다른 글

이분검색  (3) 2022.09.22
적록색약 10026 -DFS  (0) 2022.09.18
아기상어 16236 BFS  (1) 2022.09.18
안전영역 -2468 (DFS)  (1) 2022.09.18
설탕 배달-2839 (while-else문)  (0) 2022.09.16