Algorithm/DFS

[백준 14503번] 로봇 청소기

킹우현 2023. 2. 17. 17:56
import sys
input = sys.stdin.readline
from collections import deque

#방의 크기 세로(n), 가로(m)
n, m = map(int,input().split())

# 칸의 좌표(r,c), 방향(d)
r, c, d = map(int,input().split())

# 영역 초기화
area = [[0]*m for _ in range(n)]

# 방문 여부 확인 리스트
# visited = [[False]*m for _ in range(n)]

count = 0

for i in range(n):
  area[i] = list(map(int,input().split()))

def dfs(x,y,d):

  global count

  nx = [0]*4
  ny = [0]*4

  if area[x-1][y] != 0 and area[x+1][y] != 0 and area[x][y-1] != 0  and area[x][y+1] != 0:
    if (d == 0 and area[x+1][y] == 1) or (d==1 and area[x][y-1] == 1) or (d==2 and area[x-1][y]==1) or (d==3 and area[x][y+1]==1) :
      print(count)
      sys.exit()

  if area[x][y] == 0:
    area[x][y] = 2
    count+=1

  # 북쪽인 경우
  if d == 0:
    nx = [0,1,0,-1]
    ny = [-1,0,1,0]
  # 동쪽인 경우
  elif d == 1:
    nx = [-1,0,1,0]
    ny = [0,-1,0,1]
  # 남쪽인 경우
  elif d == 2:
    nx = [0,-1,0,1]
    ny = [1, 0,-1,0]
  # 서쪽인 경우
  elif d == 3:
    nx = [1,0,-1,0]
    ny = [0, 1, 0,-1]

  

  for i in range(4):
    temp_x = x + nx[i]
    temp_y = y + ny[i]

    if temp_x >= 0 and temp_x < n and temp_y >= 0 and temp_y < m:
      if area[temp_x][temp_y] == 0:
        next_x = nx[i]
        next_y = ny[i]
        if next_x == -1 and next_y == 0:
          dfs(temp_x,temp_y,0)
        elif next_x == 1 and next_y == 0:
          dfs(temp_x,temp_y,2)
        elif next_x == 0 and next_y == -1:
          dfs(temp_x,temp_y,3)
        elif next_x == 0 and next_y == 1:
          dfs(temp_x,temp_y,1)
  # if (d == 0 and area[x+1][y] == 1) or (d==1 and area[x][y-1] == 1) or (d==2 and area[x-1][y]==1) or (d==3 and area[x][y+1]==1) :
  #     print(count)
  #     sys.exit()

  
dfs(r,c,d)
print(count)