문제: https://school.programmers.co.kr/learn/courses/30/lessons/81302
Step 1. 지원자들의 위치를 찾음
Step 2. 지원자들간의 거리를 측정
- 거리가 1인 경우, 같은 행이나 열에 있는 경우에는 규정 위반
- 거리가 2인 경우, 두 지원자를 대각선의 양 끝으로 하는 직사각형 영역을 고려. 빈 책상이 있는 경우에는 규정 위반
from itertools import combinations
def init_data(places: list = None):
places_arr = [[[p for p in row] for row in room] for room in places]
return places_arr
def find_applicants(room: list = None):
height = width = len(room)
applicants_pos = []
for i in range(height):
for j in range(width):
if room[i][j] == 'P':
applicants_pos.append([i, j])
return applicants_pos
def manhatton_distance(pos1: list = None, pos2: list = None):
r1, c1 = pos1
r2, c2 = pos2
d = abs(r1-r2) + abs(c1-c2)
return d
def distance_check(pos1: None, pos2: None, room: None):
r1, c1 = pos1
r2, c2 = pos2
distance = manhatton_distance(pos1, pos2)
if distance > 2:
return True
if distance == 1:
if r1 == r2 or c1 == c2:
return False
for i in range(min(r1, r2), max(r1, r2)+1):
for j in range(min(c1, c2), max(c1, c2)+1):
if ([i, j] == pos1) or ([i, j] == pos2):
continue
if room[i][j] == 'O':
return False
return True
def room_check(room: list = None):
applicants_pos = find_applicants(room)
for pos1, pos2 in combinations(applicants_pos, 2):
if pos1 == pos2:
continue
if not distance_check(pos1, pos2, room):
return 0
return 1
def solution(places):
answer = []
place_arr = init_data(places)
for room in place_arr:
answer.append(room_check(room))
return answer
distance_check의 이중 for문을 대체할 수 없을까....
Step 1. 지원자들의 위치를 찾음
Step 2. 지원자들간의 거리를 측정
- 거리가 1인 경우, 같은 행이나 열에 있는 경우에는 규정 위반
- 거리가 2인 경우, 다음과 같은 경우에 규정위반
- 두 명의 지원자가 같은 행 또는 열에 있으나 사이에 파티션이 없는 경우
- 두 명의 지원자가 대각선에 위치하고 있으나 지원자들 사이에 파티션이 없는 경우
from itertools import combinations
def init_data(places: list = None):
places_arr = [[[p for p in row] for row in room] for room in places]
return places_arr
def find_applicants(room: list = None):
height = width = len(room)
applicants_pos = []
for i in range(height):
for j in range(width):
if room[i][j] == 'P':
applicants_pos.append([i, j])
return applicants_pos
def manhatton_distance(pos1: list = None, pos2: list = None):
r1, c1 = pos1
r2, c2 = pos2
d = abs(r1-r2) + abs(c1-c2)
return d
def distance_check(pos1: None, pos2: None, room: None):
r1, c1 = pos1
r2, c2 = pos2
distance = manhatton_distance(pos1, pos2)
if distance > 2:
return True
if distance == 1:
if r1 == r2 or c1 == c2:
return False
if r1 == r2 and room[r1][(c1+c2)//2] != 'X':
return False
if c1 == c2 and room[(r1+r2)//2][c1] != 'X':
return False
if r1 != r2 and c1 != c2: #두 사람 사이의 거리 == 2 & 대각선에 위치
if room[r1][c2] != 'X' or room[r2][c1] != 'X':
return False
return True
def room_check(room: list = None):
applicants_pos = find_applicants(room)
for pos1, pos2 in combinations(applicants_pos, 2):
if pos1 == pos2:
continue
if not distance_check(pos1, pos2, room):
return 0
return 1
def solution(places):
answer = []
place_arr = init_data(places)
for room in place_arr:
answer.append(room_check(room))
return answer