๐๏ธ Algorithm/๐ฉ ๋ฐฑ์ค
๐ฉ [๋ฐฑ์ค] [Python] 1987๋ฒ_์ํ๋ฒณ
Dbswnstjd
2022. 11. 21. 04:45
๋ฌธ์
https://www.acmicpc.net/problem/1987
1987๋ฒ: ์ํ๋ฒณ
์ธ๋ก R์นธ, ๊ฐ๋ก C์นธ์ผ๋ก ๋ ํ ๋ชจ์์ ๋ณด๋๊ฐ ์๋ค. ๋ณด๋์ ๊ฐ ์นธ์๋ ๋๋ฌธ์ ์ํ๋ฒณ์ด ํ๋์ฉ ์ ํ ์๊ณ , ์ข์ธก ์๋จ ์นธ (1ํ 1์ด) ์๋ ๋ง์ด ๋์ฌ ์๋ค. ๋ง์ ์ํ์ข์ฐ๋ก ์ธ์ ํ ๋ค ์นธ ์ค์ ํ ์นธ์ผ
www.acmicpc.net
ํ์ด
import sys
def bfs():
global cnt
queue = set([(0, 0, graph[0][0])]) # ์๊ฐ ์ด๊ณผ๋ฅผ ์ค์ด๊ธฐ ์ํด ์ค๋ณต๋๋ ๊ณณ์ ์ ๊ฑฐ
while queue:
x, y, z = queue.pop()
# ๋ง์ด ์ง๋ ์ ์๋ ์ต๋์ ์นธ ์ด๊ธฐํ
cnt = max(cnt, len(z))
# ์/ํ/์ข/์ฐ ํ์
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# ๋ฒ์ ๋ด์ ์๊ณ ์ํ๋ฒณ์ด ์ค๋ณต์ด ์๋๋ค๋ฉด ํ์
if 0 <= nx < r and 0 <= ny < c and graph[nx][ny] not in z:
queue.add((nx, ny, graph[nx][ny] + z))
r, c = map(int, sys.stdin.readline().split())
graph = [list(map(str, sys.stdin.readline().strip())) for _ in range(r)]
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
cnt = 1
bfs()
print(cnt)
BFS๋ฅผ ์ด์ฉํ ํ์ด์ธ๋ฐ ์๊ฐ์ด 1884ms ๋ก DFS๋ฅผ ์ฌ์ฉํ ํ์ด(7084ms)๋ณด๋ค ํจ์ฌ ๋น ๋ฅด๋ค๋ ๊ฒ์ ์ ์ ์๋ค.
# ๋ฐฑ์ค 1987๋ฒ ๋ฌธ์ - ์ํ๋ฒณ
# dfs ํ์ด
import sys
def dfs(x, y, z):
global cnt
# ๋ง์ด ์ง๋ ์ ์๋ ์ต๋์ ์นธ ์ด๊ธฐํ
cnt = max(cnt, z)
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# ๋ฒ์ ๋ด์ ์๊ณ ํ์ํ์ง ์์๋ค๋ฉด ํ์
if 0 <= nx < r and 0 <= ny < c and visited[graph[nx][ny]] == 0:
visited[graph[nx][ny]] = 1
dfs(nx, ny, z + 1) # ์ฌ๊ท์ ์ผ๋ก dfs ํ์
visited[graph[nx][ny]] = 0 # ์ฌ๊ท์ ์ผ๋ก ํ์ํ๋ ๊ณผ์ ์์ ํ์ถํ๊ฒ ๋๋ฉด ํ์ฌ์ ์นธ์ ํ์ ์ํ๊ฑธ๋ก ์ด๊ธฐํ
return cnt
r, c = map(int, sys.stdin.readline().split())
# ๋๋ค ํ์์ผ๋ก ๋ฌธ์๋ฅผ ์์คํค ์ฝ๋๋ก ๋ฐ๊พผ๋ค.
graph = [list(map(lambda x: ord(x)-65, sys.stdin.readline().rstrip())) for _ in range(r)]
visited = [0] * 26 # 65 ~ 90 ๊น์ง
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
cnt = 1
visited[graph[0][0]] = 1
print(dfs(0, 0, cnt))
BFS๋ก ํ๋ค๊ฐ ๋์ ํ ๋ต์ ์ฐพ๊ธฐ ๋ชปํ์ฌ DFS๋ก ํผ ํ์ด๋ฅผ ๋ณด์๋ค.
์ฌ์ค ๋ฐฉ๋ฌธํ๋ ๊ฒ์ ์ด๋ค์์ผ๋ก ํด๊ฒฐํด์ผ ํ ์ง ๋ชฐ๋ผ์ ๋๊ฒ ํค๋ฉ์์๋ค.
์ถ์ฒ