알고리즘/백준
[백준 / Python] 7576번 토마토 | 초코더
cloud_nice
2020. 1. 20. 01:10
https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마
www.acmicpc.net
접근법
다른 부분은 앞의 게시글과 거의 동일합니다. 참고해주세요!
[백준 / Python] 2178번 미로 탐색 | 초코더
https://www.acmicpc.net/problem/2178 2178번: 미로 탐색 첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다..
sinsomi.tistory.com
다른점은 앞의 문제는 queue에 첫 시작점을 넣고 다음좌표로 상하좌우 비교해 주었다면
토마토가 1인 좌표를 queue에다가 저장한후, 그 queue를 차례로 비교해주는것입니다.
나의 풀이
import sys
from collections import deque
m,n=list(map(int,sys.stdin.readline().split()))
tomato=[list(map(int,sys.stdin.readline().split())) for _ in range(n)]
visited = [[-1]*m for _ in range(n)]
dx = [-1,0,1,0]
dy = [0,1,0,-1]
queue=deque()
for i in range(n):
for j in range(m):
if tomato[i][j]==1:
visited[i][j]=0
queue.append([i,j])
while queue:
x,y=queue.popleft()
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
if tomato[nx][ny] == 0 and visited[nx][ny] == -1:
queue.append([nx,ny])
visited[nx][ny]=visited[x][y]+1
ans=max([max(row) for row in visited]) #이해안감
for i in range(n):
for j in range(m):
if tomato[i][j]==0 and visited[i][j]==-1:
ans=-1
print(ans)