티스토리 뷰

알고리즘/BOJ

[BOJ-2589] 보물섬

개발하는 후딘 2020. 3. 29. 05:20
728x90
반응형

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

 

2589번: 보물섬

보물섬 지도를 발견한 후크 선장은 보물을 찾아나섰다. 보물섬 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. 각 칸은 육지(L)나 바다(W)로 표시되어 있다. 이 지도에서 이동은 상하좌우로 이웃한 육지로만 가능하며, 한 칸 이동하는데 한 시간이 걸린다. 보물은 서로 간에 최단 거리로 이동하는데 있어 가장 긴 시간이 걸리는 육지 두 곳에 나뉘어 묻혀있다. 육지를 나타내는 두 곳 사이를 최단 거리로 이동하려면 같은 곳을 두 번 이상 지

www.acmicpc.net


[풀이]

전형적인 bfs문제이긴한데

방문체크를 해놓는다.


[코드1] Python3로하면 시간초과/ PyPy3로하면 통과(155584KB, 852ms)

import sys
from collections import deque
input=sys.stdin.readline
q=deque()

N, M= map(int, input().split())
MAP=[   [*input().strip()] for _ in range(N)]

dy=(-1,1,0,0)
dx=(0,0,-1,1)

def isRange(y,x):
    if (y>=0 and y<N) and (x>=0 and x<M):
        return True
    return False

def bfs(y,x,cnt):
    max_dist=0
    visited=[[False]*M for _ in range(N)]
    q.append((y,x,cnt))
    while q:
        y,x, cnt=q.popleft()
        if not visited[y][x]:
            visited[y][x]=True
            
            if max_dist<cnt:
                max_dist=cnt
            for i in range(4):
                nexty=y+dy[i]
                nextx=x+dx[i]
                if isRange(nexty, nextx):
                    if (not visited[nexty][nextx]) and (MAP[nexty][nextx]=='L'):
                        q.append((nexty, nextx, cnt+1))
    return max_dist #멀리떨어진 거리 리턴 
        
result=0
for y in range(N):
    for x in range(M):
        if MAP[y][x]=='L':
            result=max(result, bfs(y,x,0))
print(result)

 

[코드2] 720ms /PyPy3 통과

import sys
from collections import deque
input=sys.stdin.readline
q=deque()

N, M= map(int, input().split())
MAP=[[*input().strip()] for _ in range(N)]

dy=(-1,1,0,0)
dx=(0,0,-1,1)

def isRange(y,x):
    if (y>=0 and y<N) and (x>=0 and x<M):
        return True
    return False

def bfs(y,x,cnt):
    max_dist=0
    visited=[[False]*M for _ in range(N)]
    visited[y][x]=True #처음위치 방문
    q.append((y,x,cnt))
    
    while q:
        y,x, cnt=q.popleft()
        if max_dist<cnt:
            max_dist=cnt
        for i in range(4):
            nexty=y+dy[i]
            nextx=x+dx[i]
            if isRange(nexty, nextx):
                if (not visited[nexty][nextx]) and (MAP[nexty][nextx]=='L'):
                    q.append((nexty, nextx,cnt+1))
                    visited[nexty][nextx]=True #다음위치 미리방문
    return max_dist
        
result=0
for y in range(N):
    for x in range(M):
        if MAP[y][x]=='L':
            result=max(result, bfs(y,x,0))
print(result)

 

 

[코드3] 784ms /PyPy3

dist[y][x] 를 이용하여 거리계산

import sys
from collections import deque
input=sys.stdin.readline
q=deque()

N, M= map(int, input().split())
MAP=[[*input().strip()] for _ in range(N)]


dy=(-1,1,0,0)
dx=(0,0,-1,1)

def isRange(y,x):
    if (y>=0 and y<N) and (x>=0 and x<M):
        return True
    return False

def bfs(y,x):
    visited=[[False]*M for _ in range(N)]
    dist=[[0]*M for _ in range(N)]
    max_distance=0
    q.append((y,x))
    visited[y][x]=True #처음위치 방문
    
    while q:
        y,x=q.popleft()
        for i in range(4):
            nexty=y+dy[i]
            nextx=x+dx[i]
            if isRange(nexty, nextx):
                if (not visited[nexty][nextx]) and (MAP[nexty][nextx]=='L'):
                    q.append((nexty, nextx))
                    dist[nexty][nextx]=dist[y][x]+1
                    visited[nexty][nextx]=True #다음위치 방문
                    if max_distance<dist[nexty][nextx]:
                        max_distance=dist[nexty][nextx]
                        
    return max_distance #맨마지막 cnt를 리턴. 
        
result=0
for y in range(N):
    for x in range(M):
        if MAP[y][x]=='L':
            result=max(result, bfs(y,x))
print(result)

[실패코드]

그냥 전형적인 BFS를 사용했다.

그리고 계속 MAP[y][x]='L'일 때, 방문리스트 visited를 False로 초기화하여

가장 긴 거리를 구했다.(큐에서 마지막으로 빠져나오는 cnt)

 

언어를 Pypy3로 하면.. 메모리초과가 뜨고

Python으로하면 시간초과가 뜨고...@@;

import sys
from collections import deque
input=sys.stdin.readline
q=deque()

N, M= map(int, input().split())
MAP=[[*input().strip()] for _ in range(N)]
max_distance=0

dy=(-1,1,0,0)
dx=(0,0,-1,1)

def isRange(y,x):
    if (y>=0 and y<N) and (x>=0 and x<M):
        return True
    return False

def bfs(y,x,cnt):
    visited=[[False]*M for _ in range(N)]
    q.append((y,x,cnt))
    while q:
        y,x, cnt=q.popleft()
        visited[y][x]=True
        for i in range(4):
            nexty=y+dy[i]
            nextx=x+dx[i]
            if isRange(nexty, nextx):
                if (not visited[nexty][nextx]) and (MAP[nexty][nextx]=='L'):
                    q.append((nexty, nextx, cnt+1))
    return cnt #맨마지막 cnt를 리턴. 
        
result=0
for y in range(N):
    for x in range(M):
        if MAP[y][x]=='L':
            result=max(result, bfs(y,x,0))
print(result)
728x90
반응형

'알고리즘 > BOJ' 카테고리의 다른 글

[BOJ-15686] 치킨배달  (0) 2020.04.04
[BOJ-10159] 저울  (0) 2020.04.04
[BOJ-1182] 부분수열의 합  (0) 2020.03.28
[BOJ-1261] 알고스팟  (0) 2020.03.27
[BOJ-16936] 나3곱2  (0) 2020.03.26
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함