728x90
1. 백준 13565. 침투 (실2)
https://www.acmicpc.net/problem/13565
13565번: 침투
첫째 줄에는 격자의 크기를 나타내는 M (2 ≤ M ≤ 1,000) 과 N (2 ≤ N ≤ 1,000) 이 주어진다. M줄에 걸쳐서, N개의 0 또는 1 이 공백 없이 주어진다. 0은 전류가 잘 통하는 흰색, 1은 전류가 통하지 않
www.acmicpc.net
풀이
CODE
import sys
sys.stdin = open('input.txt', 'r')
input = sys.stdin.readline
m, n = map(int, input().split())
board = []
for _ in range(m):
board.append(list(input().rstrip()))
def dfs_stack(x, y, visited):
stack = [(x, y)]
# 현재 위치를 방문했다고 표시
visited[x][y] = True
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
while stack:
x, y = stack.pop()
# 현재 위치에서 인접한 위치 탐색
for d in range(4):
nx, ny = x + dx[d], y + dy[d]
# 배열 범위 안에 있고 방문하지 않았다면 스택에 넣고 탐색
if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny] and board[nx][ny] == '0':
if nx == m-1:
return True
else:
stack.append((nx, ny))
visited[nx][ny] = True
return False
# 방문 정보
visited = [[False] * n for _ in range(m)]
result = False
for j in range(n):
if board[0][j] == '0':
result = dfs_stack(0, j, visited)
if result:
break
print('YES' if result else 'NO')
dfs를 활용한 풀이
728x90
'알고리즘' 카테고리의 다른 글
[백준/Python] 14232. 보석도둑 (0) | 2023.09.24 |
---|---|
[백준/Python] 6064. 카잉달력 (0) | 2023.09.24 |
[백준/Python] 2725. 보이는 점의 개수 & 15988. 1, 2, 3 더하기 3 (0) | 2023.09.06 |
[프로그래머스/Python] 호텔 대실 & 배달 (0) | 2023.08.24 |
[백준/Python] 2210. 숫자판 점프 & 5567. 결혼식 (0) | 2023.08.11 |