본문 바로가기

Coding Test/Programmers

[프로그래머스/파이썬] 거리두기 확인하기

728x90

나의 풀이

from collections import deque

def check(p, x, y):
    visited = [[-1] * 5 for _ in range(5)]
    dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]
    queue = deque([(x, y, 0)])
    while queue:
        bx, by, c = queue.popleft()
        visited[bx][by] = c
        for n in range(4):
            nx, ny = bx + dx[n], by + dy[n]
            if 0 <= nx < 5 and 0 <= ny < 5 and c < 2 and p[nx][ny] != 'X' and visited[nx][ny] == -1:
                if p[nx][ny] == 'P':
                    return False
                queue.append((nx, ny, c + 1))
    return True

def solution(places):
    answer = []
    for p in places:
        flag = True
        for i in range(5):
            for j in range(5):
                if p[i][j] == 'P':
                    flag = check(p, i, j)
                    if flag == False:
                        break
            if flag == False:
                break
        if flag:
            answer.append(1)
        else:
            answer.append(0)
    return answer
반응형