😊 λ°±μ€€ 2178 : 미둜 탐색

3JuhwanΒ·2021λ…„ 2μ›” 23일
0

Algorithm

λͺ©λ‘ 보기
8/23

2178: 미둜 탐색

DFS/BFS λ‹€μ„― 번째 문제!

μ˜€λŠ˜μ€ κ΅°λŒ€ λΉ‘μ„Ό λ‚ ,,, 23μ‹œμ— λΈ”λ‘œκ·Έ κΈ€ μ“°λ‹ˆκΉŒ μ œμ •μ‹ μ΄ μ•„λ‹ˆλ‹€.


πŸ“Œ Try 1

# return -1 == λ²”μœ„ 초과 || 1 == 도착 || 0 ==  
def dfs(x, y, cnt):
    if x < 0 or x >= N or y < 0 or y >= M:
        return -1
    elif x == N-1 and y == M-1:
        result.append(cnt)
        return -1
        
    flag = 0
    
    if graph[x][y] == 1:
        graph[x][y] = 0
        
        # for j in graph:
        #     print(j)
        # print(x, y, cnt)
        
        flag += dfs(x+1, y, cnt+1)
        flag += dfs(x, y+1, cnt+1)
        flag += dfs(x-1, y, cnt+1)
        flag += dfs(x, y-1, cnt+1)
    
        if flag:
            graph[x][y] = 1
        return True
        
    return 0

N, M = map(int, input().split())
graph, result = [], []

for _ in range(N):
    graph.append(list(map(int, input())))

dfs(0, 0, 1)

print(min(result))

더 μ΅μˆ™ν•œ dfs둜 ν’€μ—ˆλŠ”λ°,,, λŸ°νƒ€μž„μ—λŸ¬κ°€ λ–΄λ‹€.
μž…μΆœλ ₯ μ˜ˆμ‹œκ°€ 잘 좜λ ₯λ˜μ„œ κ·Έλƒ₯ λ„£μ—ˆλŠ”λ°, μ—­μ‹œλ‚˜ 였λ₯˜κ°€ λ§Žμ•˜λ‹€.

λ‚΄ 생각에 λ¬Έμ œλŠ”, μž¬κ·€ ν•¨μˆ˜μ˜ μ‹€ν–‰ μˆœμ„œλ₯Ό 잘 λͺ¨λ₯Έ μ±„λ‘œ μ½”λ“œλ₯Ό 막 μ§°κΈ° λ•Œλ¬Έμ΄λ‹€.

μ•„λ¬΄νŠΌ, κ²€μƒ‰ν•΄λ³΄λ‹ˆ dfsλŠ” μ΅œλ‹¨ 거리 λ¬Έμ œμ—” λΆˆλ¦¬ν•˜λ‹€κ³  λ‚˜μ™€μžˆμ–΄μ„œ λ‹€μŒ μ½”λ“œλŠ” bfs둜 μž‘μ„±ν–ˆλ‹€.


πŸ“Œ Try 2

from collections import deque

def bfs(x, y):
    queue = deque()
    queue.append((x, y))
    
    while queue:
        # x, y, num 에 ν˜„μž¬ 데이터 μ €μž₯
        x, y = queue.popleft()
        num = graph[x][y]
        
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            
            # 상 ν•˜ 쒌 우 λ…Έλ“œ 검사
            if nx < 0 or nx >= N or ny < 0 or ny >= M:
                continue
            
            # 1 이면, queue에 λ„£μŒ
            # ν˜„μž¬ λ…Έλ“œμ— 이전 λ…Έλ“œ 값을 λ”ν•˜κΈ°
            if graph[nx][ny] == 1:
                graph[nx][ny] += num
                queue.append((nx, ny))
        
    return graph[N-1][M-1]

N, M = map(int, input().split())
graph = []

for _ in range(N):
    graph.append(list(map(int, input())))

# 상 ν•˜ 쒌 우
dx = [-1, 1, 0 ,0]
dy = [0, 0, -1, 1]

print(bfs(0, 0))

μ΄λ²ˆμ—” bfs둜 μž‘μ„±ν–ˆλ‹€.
μ—¬λŸ¬ λΈ”λ‘œκ·Έμ™€ μ˜μƒμ„ μ°Έκ³ ν•΄μ„œ μž‘μ„±ν–ˆμ§€λ§Œ, κ·Έλž˜λ„ λ‚˜λ¦„ 많이 κ³ λ―Όν–ˆλ‹€.

μƒν•˜μ’Œμš°μ™€ κ΄€λ ¨λœ 뢀뢄을 κ°„κ²°ν•˜κ²Œ 짜기 μœ„ν•΄ λ‚˜λ™λΉˆ 유튜브λ₯Ό μ°Έκ³ ν–ˆλ‹€. 근데 κ²°κ΅­ μ½”λ“œλŠ” 거의 μœ μ‚¬ν•˜λ‹€.


🎁 Reference

profile
Codeforces와 USACO 풀이λ₯Ό κΈ°λ‘ν•©λ‹ˆλ‹€. 이전 글도 계속 μ—…λ°μ΄νŠΈ λ©λ‹ˆλ‹€.

0개의 λŒ“κΈ€