Algorithm

[λ°±μ€€] 2178. 미둜 탐색 python

🐳 링크

λ°±μ€€ 2178번 λ―Έλ‘œνƒμƒ‰

πŸ• 문제

NΓ—M크기의 λ°°μ—΄λ‘œ ν‘œν˜„λ˜λŠ” λ―Έλ‘œκ°€ μžˆλ‹€.

1 0 1 1 1 1
1 0 1 0 1 0
1 0 1 0 1 1
1 1 1 0 1 1

λ―Έλ‘œμ—μ„œ 1은 이동할 수 μžˆλŠ” 칸을 λ‚˜νƒ€λ‚΄κ³ , 0은 이동할 수 μ—†λŠ” 칸을 λ‚˜νƒ€λ‚Έλ‹€. μ΄λŸ¬ν•œ λ―Έλ‘œκ°€ μ£Όμ–΄μ‘Œμ„ λ•Œ, (1, 1)μ—μ„œ μΆœλ°œν•˜μ—¬ (N, M)의 μœ„μΉ˜λ‘œ 이동할 λ•Œ μ§€λ‚˜μ•Ό ν•˜λŠ” μ΅œμ†Œμ˜ μΉΈ 수λ₯Ό κ΅¬ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ‹œμ˜€. ν•œ μΉΈμ—μ„œ λ‹€λ₯Έ 칸으둜 이동할 λ•Œ, μ„œλ‘œ μΈμ ‘ν•œ 칸으둜만 이동할 수 μžˆλ‹€.

μœ„μ˜ μ˜ˆμ—μ„œλŠ” 15칸을 μ§€λ‚˜μ•Ό (N, M)의 μœ„μΉ˜λ‘œ 이동할 수 μžˆλ‹€. 칸을 μ…€ λ•Œμ—λŠ” μ‹œμž‘ μœ„μΉ˜μ™€ 도착 μœ„μΉ˜λ„ ν¬ν•¨ν•œλ‹€.

🐾 풀이 방법

  1. n,mκ³Ό miroλ₯Ό μ°¨λ‘€λŒ€λ‘œ λ°›μ•„μ€€λ‹€.
    • μ΄λ•Œ, miro에 λ“€μ–΄μ˜€λŠ” 값듀은 μˆ«μžκ°€ λΆ™μ–΄μ„œ λ“€μ–΄μ˜€λ―€λ‘œ str으둜 받은 채 listν™” ν•˜μ—¬ μ΄μš©ν•˜λŠ” 것이 νŽΈν•˜λ‹€.
  2. (0,0)λΆ€ν„° μ‹œμž‘ν•˜μ—¬ 이웃 λ…Έλ“œλ“€μ„ λ°©λ¬Έν•œλ‹€.
  3. λ°©λ¬Έν•  λ•Œ, visit λ°°μ—΄μ˜ 값에 이전 visit 배열에 μ €μž₯된 κ°’ + 1을 ν•΄μ€€λ‹€.
  • μ΄μœ λŠ”, μ‹œκ°„ 초과λ₯Ό ν•΄κ²°ν•˜κΈ° μœ„ν•΄μ„œμ΄λ‹€. λ‹€μ‹œ 제일 처음으둜 λŒμ•„κ°€λŠ” 것이 μ•„λ‹Œ 이전 값에 +1을 ν•¨μœΌλ‘œμ¨ μ΅œμ’… (n-1,m-1)에 λ„λ‹¬ν•˜μ˜€μ„ λ•Œ μ΅œμ†Ÿκ°’μ„ visit 배열에 μ €μž₯ν•  수 μžˆλ‹€.

solution μ½”λ“œ

  1. bfs둜 solveν•œ μ½”λ“œ
    import sys
    sys.setrecursionlimit(10**8)
    sys.stdin = open("input.txt","rt")
    

dx = [1,-1,0,0]
dy = [0,0,1,-1]

n,m = [int(x) for x in sys.stdin.readline().split()]
answer = n*m + 1
visit = [[0] * m for _ in range(n)]
visit[0][0] = 1
miro = [list(sys.stdin.readline().strip()) for _ in range(n)]

q = []
q.append((0,0))
while q:
x, y = q.pop(0)
if x == n-1 and y == m-1:
print(visit[x][y])
sys.exit()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m:
if visit[nx][ny] == 0 and miro[nx][ny] == '1':
visit[nx][ny] = visit[x][y] + 1
q.append((nx,ny))


2. dfs둜 μ‹œκ°„μ΄ˆκ³Ό μ½”λ“œ
bfs둜 문제λ₯Ό λ‹€μ‹œ 풀어보며 λ“  생각이, (n,m)κΉŒμ§€μ˜ μ΅œλ‹¨ 거리λ₯Ό κ΅¬ν•˜λŠ” λ¬Έμ œμ΄λ―€λ‘œ dfs처럼 μ²˜μŒλΆ€ν„° (n,m)κΉŒμ§€ λ„λ‹¬ν•œ λ’€ λ’€λ‘œ λΉ μ Έλ‚˜μ˜€λ©° λ‹€λ₯Έ 경둜λ₯Ό νƒμƒ‰ν•˜λŠ” λ°©λ²•λ³΄λ‹€λŠ” bfs처럼 이웃 λ…Έλ“œλ“€μ„ λͺ¨λ‘ νƒμƒ‰ν•˜μ—¬ visit에 경둜 값을 λˆ„μ ν•œ λ’€, μ΅œμ’… λ„λ‹¬ν–ˆμ„ λ•Œ visit[n-1][m-1]의 값을 좜λ ₯ν•˜λŠ” 것이 더 λΉ λ₯΄κ³ , μ •ν™•ν•œ λ°©λ²•μ΄λΌλŠ” 생각이 λ“€μ—ˆλ‹€. 

```python3
import sys
sys.setrecursionlimit(10**8)
sys.stdin = open("input.txt","rt")

dx = [1,-1,0,0]
dy = [0,0,1,-1]

def dfs(x,y, cnt):
    global answer
    if x == n-1 and y == m-1:
        answer = cnt if answer > cnt else answer
    else:
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if 0 <= nx < n and 0 <= ny < m and visit[nx][ny] == 0 and miro[nx][ny] == '1':
                visit[nx][ny] = 1
                dfs(nx,ny,cnt+1)
                visit[nx][ny] = 0



n,m = [int(x) for x in sys.stdin.readline().split()]
answer = n*m + 1
visit = [[0] * m for _ in range(n)]
visit[0][0] = 1
miro = [list(sys.stdin.readline().strip()) for _ in range(n)]

# miro = [sys.stdin.readline().rstrip() for _ in range(n)]

dfs(0,0,1)
print(answer)