๋ฐ์ํ
๐ฑ ๋ฌธ์
๐ฑ ํ์ด
0. ๊ธฐ๋ณธ ๋ก์ง
safe_zone = []
idx = 1
for i in range(n):
for j in range(m):
if visited[i][j] == False:
dfs(board, i, j, visited)
idx += 1
- ๋ฐฉ๋ฌธํ์ง ์์ ๋
ธ๋๋ฅผ ๋๋ฉด์
dfs
ํ์์ ํฉ๋๋ค. dfs
ํจ์์์ ๋ฌด์กฐ๊ฑด ํ๋์ ์ฌ์ดํด์ด ์ฐพ์์ง๋ฏ๋กdfs
ํจ์๋ฅผ ์ํํ๊ณ ๋์ค๋ฉดidx
๊ฐ์ ์ฆ๊ฐ์ํต๋๋ค.
1. dfs
ํจ์
def dfs(board, x, y, visited):
global idx
if x < 0 or y < 0 or x > n - 1 or y > m - 1:
return 0
if visited[x][y] != False:
if visited[x][y] == idx:
safe_zone.append((x, y))
return 1
visited[x][y] = idx
dx, dy = movements[board[x][y]]
nx, ny = x + dx, y + dy
dfs(board, nx, ny, visited)
- ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ๋ฅผ ํ์ฌ ๋๊ณ ์๋ ์ฌ์ดํด์ ๋ฒํธ์ธ
idx
๋ก ํ์ํฉ๋๋ค. - ์ด๋ ์ ๋ ฅ๋ฐ์ ๋ฐฉํฅ(D, U, L, R)์ ๋ฐ๋ผ dfs ํ์์ ํ์ ๋, ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๋ ธ๋๋ผ๋ฉด ์ฌ์ดํด์ด ์์ฑ๋ ๊ฒ์ ๋๋ค.
- ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๋
ธ๋์ ๋ฐฉ๋ฌธ์ฒ๋ฆฌ๋ ๊ฐ(
idx
)์ด ํ์ฌ ๋๊ณ ์๋ ์ฌ์ดํด์ ๋ฒํธ์ ๊ฐ๋ค๋ฉด ์๋ก์ด ์ฌ์ดํด์ด ๋ง๋ค์ด์ง ๊ฒ์ด๋ฏ๋กsafe_zone
์ ํ์ฌ ์์น๋ฅผ ์ถ๊ฐํฉ๋๋ค. ๊ทธ๋ ์ง ์์ผ๋ฉด ์ด๋ฏธ ๋ง๋ค์ด์ง ์ฌ์ดํด์ ํ์ฌ ์์น๊ฐ ํฌํจ๋์ด์ผ ํ๋ ๊ฒ์ด๋ฏ๋กsafe_zone
์ ์ถ๊ฐํ์ง ์๊ณ ๋ฆฌํดํฉ๋๋ค.
๐ฑ ์ฝ๋
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# boj 16724 ํผ๋ฆฌ ๋ถ๋ ์ฌ๋์ด
import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int, input().split())
board = []
for _ in range(n):
board.append(list(map(str, input().rstrip())))
# ๋ฐฉํฅ ์ค์
movements = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
visited = [[False] * m for _ in range(n)]
def dfs(board, x, y, visited):
global idx
if x < 0 or y < 0 or x > n - 1 or y > m - 1:
return 0
if visited[x][y] != False:
if visited[x][y] == idx:
safe_zone.append((x, y))
return 1
visited[x][y] = idx
dx, dy = movements[board[x][y]]
nx, ny = x + dx, y + dy
return dfs(board, nx, ny, visited)
safe_zone = []
idx = 1
for i in range(n):
for j in range(m):
if visited[i][j] == False:
dfs(board, i, j, visited)
idx += 1
print(len(safe_zone))
๋ฐ์ํ
'Algorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] #2437 ์ ์ธ (Python, Greedy) (0) | 2023.03.19 |
---|---|
[BOJ] #11000 ๊ฐ์์ค ๋ฐฐ์ (Python, ์ฐ์ ์์ ํ, ๊ทธ๋ฆฌ๋) (2) | 2023.03.17 |
[BOJ] #1027 ๊ณ ์ธต ๊ฑด๋ฌผ(Bruteforce, Python) (0) | 2023.02.28 |
[BOJ] #1450 ๋ ์๋ฌธ์ (์ด๋ถ ํ์, Python) (0) | 2023.02.27 |
[BOJ] #2110 ๊ณต์ ๊ธฐ ์ค์น (์ด๋ถํ์, Python) (0) | 2023.02.26 |
๋๊ธ