๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[๋ฐฑ์ค 2178] ๋ฏธ๋ก ํ์ (Python)
โ๏ธIdea Sketch
2021-07-28
1. ๋ฐฑ์ค ์ ๋ ฅ๊ฐ ์ฒ๋ฆฌ์์ ํค๋งธ๋ ๋ฌธ์
- sys.stdin.readline() : ํ ์ค์ ์ ๋ ฅ๋ฐ์ผ๋ฉฐ, input()๊ณผ ๋น์ทํ๋ค.
- split() : ๋์ด์ฐ๊ธฐ๋ฅผ ๊ธฐ์ค์ผ๋ก ์์๋ฅผ ๋๋๋ค.
- rstrip() : ์ฐ์ธก \n๋ฅผ ์ ๊ฑฐํ๋ค.
- list(map(int, sys.stdin.readline().rstrip())) : ํ ์ค ์ ๋ ฅ๋ฐ๊ณ , ์ฐ์ธก \n์ ์ ๊ฑฐํ ํ, ๋ชจ๋ ์์๋ฅผ intํ์ผ๋ก ๋ณํํ ๋ฐฐ์ด์ ์์ฑํ๋ค.
N, M = map(int, sys.stdin.readline().split())
graph = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(N)]
2. dx์ dy๋ฅผ ์ ์ํ๊ณ , graph ๊ฒฝ๊ณ๊ฐ ์ฒ๋ฆฌ
3. visited ์๋ต๊ฐ๋ฅ
โ๏ธ์์ค์ฝ๋
2021-07-28
112ms ํต๊ณผ, visited ์ฌ์ฉ
import sys
from collections import deque
N, M = map(int, sys.stdin.readline().split())
graph = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(N)]
visited = [[0 for _ in range(M)] for _ in range(N)]
def bfs(x, y):
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
queue = deque([(x, y)])
visited[x][y] = 1
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if (-1<nx<N) and (-1<ny<M): #1 ๊ฒฝ๊ณ๊ฐ [#1๋ถํฐ #3๊น์ง ํ ์ค๋ก ์์ฑํ ๊ฒฝ์ฐ 124ms]
if graph[nx][ny]: #2 ๋ฒฝ์ธ์ง ์๋์ง
if not visited[nx][ny]: #3 ๋ฐฉ๋ฌธ์ฌ๋ถ
queue.append((nx, ny))
visited[nx][ny] = visited[x][y] + 1
return visited[N-1][M-1]
print(bfs(0, 0))
124ms ํต๊ณผ, visited ์๋ต
- graph[nx][ny]๊ฐ 0์ด๋ฉด ๋ฒฝ
- graph[nx][ny]๊ฐ 1์ด๋ฉด ์ฒ์ ๋ฐฉ๋ฌธํ ๋ ธ๋
- graph[nx][ny]๊ฐ 1๋ณด๋ค ํฌ๋ฉด ๋ฐฉ๋ฌธํ ์ ์๋ ๋ ธ๋
import sys
from collections import deque
N, M = map(int, sys.stdin.readline().split())
graph = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(N)]
def bfs(x, y):
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
queue = deque([(x, y)])
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if (-1<nx<N) and (-1<ny<M):
if graph[nx][ny] == 1:
queue.append((nx, ny))
graph[nx][ny] = graph[x][y] + 1
return graph[N-1][M-1]
print(bfs(0, 0))