[백준] 9205 맥주 마시면서 걸어가기 Python

권희정·2024년 9월 30일

삼성전자

목록 보기
11/20

[백준] 9205 맥주 마시면서 걸어가기 Python

처음에는 상하좌우를 탐색하면서 진행해야하나 생각했지만, 다른 사람들의 풀이를 보니 편의점과의 거리를 체크하면 되는 것이였다.
BFS 함수를 구현할 때, 홈의 위치를 먼저 넣어주고, 꺼낸 뒤 =<20x50=1000 이면 return True를 해주도록 했고, 되지 않는 경우에는 편의점 거리를 넣어주어 거리를 update 해줬다.

import sys
sys.stdin=open("input.txt")
from collections import deque
def bfs(si,sj,gi,gj,conbi):
    q=deque()
    q.append((si,sj))

    while q:
        x,y=q.popleft()

        if abs(gi-x)+abs(gj-y)<=1000:
            return True
        for i in range(n): #편의점
            if not visited[i]:
                nx,ny=conbi[i]
                if abs(nx-x)+abs(ny-y)<=1000:
                    visited[i]=True
                    q.append((nx,ny))
    return False

t=int(input())
for _ in range(t):
    n=int(input()) #편의점 개수
    hx,hy=map(int,input().split()) #상근이네 집
    conbi=[]
    for _ in range(n):
        px,py=map(int,input().split())
        conbi.append((px,py))
    rx,ry=map(int,input().split()) #락페스티벌 좌표
    visited=[False for _ in range(n)]

    if bfs(hx,hy,rx,ry,conbi):
        print('happy')
    else:
        print('sad')
profile
데헷큥

0개의 댓글