백준 17086번 아기 상어 2 (Python 3)
2022. 8. 30. 17:58ㆍProblem solving
Baekjoon online judge 17086번 파이썬
링크
https://www.acmicpc.net/problem/17086
17086번: 아기 상어 2
첫째 줄에 공간의 크기 N과 M(2 ≤ N, M ≤ 50)이 주어진다. 둘째 줄부터 N개의 줄에 공간의 상태가 주어지며, 0은 빈 칸, 1은 아기 상어가 있는 칸이다. 빈 칸과 상어의 수가 각각 한 개 이상인 입력만
www.acmicpc.net
모든 0인 점에 대해서 bfs를 수행, 1을 만나면 now_max에 값을 반영하고 bfs종료
데이터가 커지면 복잡도가 너무 커져서 이 방법으로는 못풀것같다.
더 효율적인 풀이가 있을것 같다.
+추가
bfs가 필요 없었다.
1의 위치를 미리 저장해놓고, 각 0에 대해서 1의 위치들과의 거리를 구한다. 그 중에 최소값을 now_max에 반영하면 bfs없이도 풀수있다. 이 쪽이 1이 적을 떄는 훨씬 빠르다.
소스코드
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
def bfs(x,y):
global now_max
queue=deque()
queue.append([x,y,0])
visited=[[False for _ in range(m)] for _ in range(n)]
visited[y][x]=True
while queue:
qx,qy,cnt=queue.popleft()
if map_data[qy][qx]==1:
now_max=max(now_max,cnt)
return
for indx,indy in index:
nx=qx+indx
ny=qy+indy
if 0<=nx<m and 0<=ny<n and not visited[ny][nx]:
visited[ny][nx]=True
queue.append([nx,ny,cnt+1])
n,m=map(int,input().split())
index=[[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]
map_data=[list(map(int,input().split())) for _ in range(n)]
now_max=-1
for i in range(n):
for j in range(m):
if map_data[i][j]==0:
bfs(j,i)
print(now_max)
'Problem solving' 카테고리의 다른 글
백준 17142번 연구소 3 (Python 3) (0) | 2022.08.30 |
---|---|
백준 17141번 연구소 2 (Python 3) (0) | 2022.08.30 |
백준 5014번 스타트링크 (Python 3) (0) | 2022.08.30 |
백준 14395번 4연산 (Python 3) (0) | 2022.08.30 |
백준 1963번 소수 경로 (Python 3) (0) | 2022.08.30 |