Problem Solving/프로그래머스

프로그래머스 거리두기 확인하기

minOE 2025. 7. 11. 07:01
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/81302

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

from collections import deque

def bfs(q,graph):
    x,y =  q.popleft()
    for dx,dy in {(1,0),(0,1),(-1,0),(0,-1),(-1,1),(1,-1),(1,1),(-1,-1),(0,2),(0,-2),(-2,0),(2,0)} :
        nx = x + dx
        ny = y + dy
        if 0<=nx < 5 and 0<= ny < 5 and not visited[nx][ny] and  graph[nx][ny] == "P" :
            q.append((nx,ny))
            visited[nx][ny]=1
            while q:
                nnx,nny = q.popleft()
                for kx,ky in {(1,0),(0,1),(-1,0),(0,-1),}:
                    nkx = nnx+kx
                    nky = nny+ky
                    if 0<=nkx < 5 and 0<= nky < 5 and (abs(nx-nnx) + abs(ny-nny)) <2 and not visited[nkx][nky] and graph[nkx][nky]== "O": 
                        q.append((nkx,nky))
                        visited[nkx][nky] =1
                    if 0<=nkx < 5 and 0<= nky < 5 and (abs(nx-nnx) + abs(ny-nny)) <2  and not visited[nkx][nky] and graph[nkx][nky]== "P":
                        visited[nkx][nky] =1
                        return False
    return True
    
    

def fun(graph):
    global visited
    visited = [[0 for _ in range(5)] for _ in range(5)]
    flag = True
    q = deque()
    for i in range(5):
        for j in range(5):
            if graph[i][j] == "X":
                visited[i][j] =1
    for i in range(5):
        for j in range(5):
            if graph[i][j] == "P":
                q.append((i,j))
                if not bfs(q,graph):
                    flag = False
                    break
    if not flag:
        return 0
    return 1
    
                
def solution(places):
    ans =[]
    for i in range(len(places)):
        ans.append(fun(places[i]))
    return ans

 

오랜만에 머리를 좀 썼다 ..

728x90