Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] 2178๋ฒˆ - ๋ฏธ๋กœํƒ์ƒ‰ (ํŒŒ์ด์ฌ)

๊ฐ์ž ๐Ÿฅ” 2021. 10. 14. 16:04
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ๋งํฌ

https://www.acmicpc.net/problem/2178

 

2178๋ฒˆ: ๋ฏธ๋กœ ํƒ์ƒ‰

์ฒซ์งธ ์ค„์— ๋‘ ์ •์ˆ˜ N, M(2 ≤ N, M ≤ 100)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” M๊ฐœ์˜ ์ •์ˆ˜๋กœ ๋ฏธ๋กœ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ๊ฐ์˜ ์ˆ˜๋“ค์€ ๋ถ™์–ด์„œ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

 

๋‚˜์˜ํ’€์ด

  1. ๋Œ€๋ถ€๋ถ„์˜ ๊ทธ๋ž˜ํ”„ํƒ์ƒ‰ ๋ฌธ์ œ๋Š” dfs,dfs๋กœ ํ’€๋ฆฌ๊ณ  dx, dy๋ฅผ ํ™œ์šฉํ•˜์—ฌ ํ’€๋ฉด ๋œ๋‹ค๋Š” ์‚ฌ์‹ค์„ ์•Œ๊ฒŒ๋˜์—ˆ๋‹ค.
  2. ์ดˆ๋ฐ˜์— ๋ฐฉ๋ฌธํ•˜๊ณ ์žํ•˜๋Š” ๋…ธ๋“œ๋ฅผ 0,0์œผ๋กœ ๋†“๊ณ  ํ•˜๋‚˜์”ฉ ์ฃผ๋ณ€ ๋…ธ๋“œ๋ฅผ ๊ฒ€์ƒ‰ํ•ด๊ฐ€๋ฉฐ ์˜ฎ๊ฒจ๊ฐ€๋ฉด๋œ๋‹ค!
  3. ํ•ด๋‹น ๋ฌธ์ œ์ฒ˜๋Ÿผ ๋งˆ์ง€๋ง‰์— "์ตœ๋‹จ๊ฑฐ๋ฆฌ"๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์™€ ๊ฐ™์ด ์œ„์น˜๊ฐ€ ์•„๋‹ˆ๋ผ ์ง„ํ–‰์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๋ฉด +=1์”ฉ ํ•ด๋‚˜์•„๊ฐ„ ํ–‰๋ ฌ์„ ํ•˜๋‚˜ ๋” ๋งŒ๋“  ํ›„(ํ•ด๋‹น ๋ฌธ์ œ์—์„œ dist) ๊ตฌํ•ด์ฃผ๋Š”๊ฒƒ์ด ํŽธํ•˜๋‹ค.
from collections import deque
n,m = map(int, input().split())
matrix = [list(map(int, list(input()))) for _ in range(n)]

visited = [[False] * m for _ in range(n)]
dist = [[0] * m for _ in range(n)] #๊ฑฐ๋ฆฌ +1 ์”ฉ ํ•ด์ค„๊ฑฐ๊ณ  ๋งˆ์ง€๋ง‰์— ์ด๊ฑฐ ์ถœ๋ ฅํ• ๊ฑฐ์ž„
queue = deque()
queue.append((0,0)) #์‹œ์ž‘์ 
dist[0][0] = 1 #์‹œ์ž‘์  ๊ฑฐ๋ฆฌ๋Š” 1๋กœ ํ•ด์คŒ

#๋ฐฉํ–ฅํ‚ค
#dx[0] dx[0] : ์™ผ์ชฝ
#dx[1] dx[1] : ์˜ค๋ฅธ์ชฝ
#dx[2] dx[2] : ์œ„
#dx[3] dx[3] : ์•„๋ž˜
dx = [0,0,-1,1]
dy = [-1,1,0,0]

while queue:
    x, y = queue.popleft()
    for i in range(4):
        nx, ny = x + dx[i], y + dy[i]
        if 0  <= nx < n and 0 <= ny < m:#๊ทธ๋ž˜ํ”„ ๋ฒ—์–ด๋‚˜๋ฉด ์•ˆ๋ผ
            if visited[nx][ny] == False and matrix[nx][ny] == 1: #๋ฐฉ๋ฌธ๋…ธ๋“œ๊ฐ€ ์•„๋‹ˆ๊ณ , matrix์— 1์ด ์žˆ๋Š”์œ„์น˜๋ฉด ์œ„์น˜ ๋ฐ”๊ฟ”์ฃผ๊ธฐ
                queue.append((nx, ny))
                dist[nx][ny] += dist[x][y] + 1 #dist์—์„œ x,y๋Š” 1์ด๋‹ˆ๊นŒ ๊ทธ๊ฑฐ๋ณด๋‹ค +1 ํ•ด์ค˜์„œ ๋„ฃ์–ด์คŒ (2)
                visited[nx][ny] = True #๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ๊นŒ์ง€
                
print(dist[n-1][m-1]) #n,m์€ ๊ฐฏ์ˆ˜๋‹ˆ๊นŒ ํ–‰๋ ฌ์—์„œ๋Š” -1์”ฉ

 

๋ฐ˜์‘ํ˜•