|
| 1 | +""" |
| 2 | +PGS #81032. 거리두기 확인하기 (Level 2) |
| 3 | +https://school.programmers.co.kr/learn/courses/30/lessons/81302 |
| 4 | +유형: Brute Force, Graph, BFS |
| 5 | +""" |
| 6 | + |
| 7 | +""" |
| 8 | +풀이1: 완전 탐색 |
| 9 | +""" |
| 10 | + |
| 11 | + |
| 12 | +def solution(places): |
| 13 | + def is_safe(place): |
| 14 | + for i in range(5): |
| 15 | + for j in range(5): |
| 16 | + if place[i][j] != 'P': |
| 17 | + continue |
| 18 | + |
| 19 | + for dx, dy in dirs: |
| 20 | + ni, nj = i + dx, j + dy |
| 21 | + if not (0 <= ni < 5 and 0 <= nj < 5): |
| 22 | + continue |
| 23 | + if place[ni][nj] != 'P': |
| 24 | + continue |
| 25 | + |
| 26 | + dist = abs(dx) + abs(dy) |
| 27 | + if dist == 1: |
| 28 | + return 0 # 거리 1에서 바로 P면 위반 |
| 29 | + elif dist == 2: |
| 30 | + # 파티션 여부 확인 |
| 31 | + if dx == 0: # 수평 |
| 32 | + if place[i][j + dy // 2] != 'X': |
| 33 | + return 0 |
| 34 | + elif dy == 0: # 수직 |
| 35 | + if place[i + dx // 2][j] != 'X': |
| 36 | + return 0 |
| 37 | + else: # 대각선 |
| 38 | + if place[i][nj] != 'X' or place[ni][j] != 'X': |
| 39 | + return 0 |
| 40 | + return 1 |
| 41 | + |
| 42 | + dirs = [ |
| 43 | + (-1, 0), (1, 0), (0, -1), (0, 1), # 거리 1 |
| 44 | + (-2, 0), (2, 0), (0, -2), (0, 2), # 일직선 거리 2 |
| 45 | + (-1, -1), (-1, 1), (1, -1), (1, 1) # 대각선 거리 2 |
| 46 | + ] |
| 47 | + |
| 48 | + answer = [] |
| 49 | + for place in places: |
| 50 | + answer.append(is_safe(place)) |
| 51 | + |
| 52 | + return answer |
| 53 | + |
| 54 | + |
| 55 | +""" |
| 56 | +풀이2: BFS |
| 57 | +""" |
| 58 | +from collections import deque |
| 59 | + |
| 60 | + |
| 61 | +def bfs(p): |
| 62 | + start = [] |
| 63 | + |
| 64 | + for i in range(5): # 시작점이 되는 P 좌표 구하기 |
| 65 | + for j in range(5): |
| 66 | + if p[i][j] == 'P': |
| 67 | + start.append([i, j]) |
| 68 | + |
| 69 | + for s in start: |
| 70 | + queue = deque([s]) # 큐에 초기값 |
| 71 | + visited = [[0] * 5 for i in range(5)] # 방문 처리 리스트 |
| 72 | + distance = [[0] * 5 for i in range(5)] # 경로 길이 리스트 |
| 73 | + visited[s[0]][s[1]] = 1 |
| 74 | + |
| 75 | + while queue: |
| 76 | + y, x = queue.popleft() |
| 77 | + |
| 78 | + dx = [-1, 1, 0, 0] # 좌우 |
| 79 | + dy = [0, 0, -1, 1] # 상하 |
| 80 | + |
| 81 | + for i in range(4): |
| 82 | + nx = x + dx[i] |
| 83 | + ny = y + dy[i] |
| 84 | + |
| 85 | + if 0 <= nx < 5 and 0 <= ny < 5 and visited[ny][nx] == 0: |
| 86 | + |
| 87 | + if p[ny][nx] == 'O': |
| 88 | + queue.append([ny, nx]) |
| 89 | + visited[ny][nx] = 1 |
| 90 | + distance[ny][nx] = distance[y][x] + 1 |
| 91 | + |
| 92 | + if p[ny][nx] == 'P' and distance[y][x] <= 1: |
| 93 | + return 0 |
| 94 | + return 1 |
| 95 | + |
| 96 | + |
| 97 | +def solution(places): |
| 98 | + answer = [] |
| 99 | + |
| 100 | + for i in places: |
| 101 | + answer.append(bfs(i)) |
| 102 | + |
| 103 | + return answer |
0 commit comments