1+ """
2+ 2hour
3+ - 직사각형 바깥 테두리 이동
4+ - x축, y축 좌표가 같은 경우 없음(꼭짓점, 변 공유 x )
5+ - 분리x, 포함x => only 겹침
6+ goal) 캐릭터(start) -> 아이템 최단거리(BFS)
7+
8+ #key idea : 좌표 & grid 2배 처리하기
9+ (참고.https://jyeonnyang2.tistory.com/247#google_vignette)
10+ #1. 인접 행렬
11+ -field[x][y] = 길에 해당하는 (x,y) 칸 = 1 ,길 x 인 칸은 (x,y )= 0
12+
13+ -(1) 각 직사각형 테두리에 해당하는 좌표 선출
14+ - (2) A- > B 각 범위에 겹치는 테두리 자표 제거[필터링]
15+ -> 내부 빈 공간은 상관x
16+ #2. BFS
17+ - visited 사용 to 누적 거리
18+ """
19+ from collections import deque
20+ def get_outlier (x1 ,y1 ,x2 ,y2 ):
21+
22+ pos_outliers = list ()
23+ # 가로
24+ for x in range (x1 ,x2 + 1 ,1 ):
25+ pos_outliers .append ([x ,y1 ])
26+ pos_outliers .append ([x ,y2 ])
27+ # 세로
28+ for y in range (y1 , y2 + 1 , 1 ):
29+ if [x1 ,y ] in pos_outliers or [x2 ,y ] in pos_outliers :
30+ continue
31+ pos_outliers .append ([x1 ,y ])
32+ pos_outliers .append ([x2 ,y ])
33+ return sorted (pos_outliers )
34+
35+
36+ def solution (rectangle , characterX , characterY , itemX , itemY ):
37+ answer = 0
38+ field = [[0 for _ in range (51 * 2 )] for k in range (51 * 2 )]
39+ #인접 행렬
40+ characterX , characterY = characterX * 2 , characterY * 2
41+ itemX , itemY = itemX * 2 , itemY * 2
42+ #1.각 직사각형 칸 획득
43+ for k in range (len (rectangle )):
44+ #outlier 칸 찾기
45+ x1 ,y1 ,x2 ,y2 = rectangle [k ]
46+ x1 = x1 * 2 ; x2 = x2 * 2 ; y1 = y1 * 2 ; y2 = y2 * 2 # 2배
47+ outliers = get_outlier (x1 ,y1 ,x2 ,y2 )
48+
49+ #필터링
50+ # 모든 변 = 1 - 영역 겹치는 모서리만 =0
51+ for i in range (len (outliers )):
52+ out_x , out_y = outliers [i ]
53+ field [out_x ][out_y ] = 1
54+ # 영역 겹치는 모서리 탐색 -> =0
55+ for j in range (len (rectangle )) :
56+ if j == k : # 본인껀 스킵
57+ continue
58+ fil_x1 , fil_y1 , fil_x2 , fil_y2 = rectangle [j ]
59+ fil_x1 , fil_y1 = fil_x1 * 2 , fil_y1 * 2
60+ fil_x2 , fil_y2 = fil_x2 * 2 , fil_y2 * 2
61+ for i in range (len (outliers )):
62+ out_x , out_y = outliers [i ]
63+ # 면적이 겹침 -> 필터링
64+ if fil_x2 > out_x > fil_x1 and fil_y2 > out_y > fil_y1 :
65+ field [out_x ][out_y ] = 0
66+
67+ # for i in range(51):
68+ # for k in range(51):
69+ # if field[i][k] == 1:
70+ # print (f"[{i},{k}")
71+
72+ # stage 2. BFS로 최단 거리 찾기
73+ # 상하좌우
74+ dx = [0 ,0 ,1 ,- 1 ]
75+ dy = [1 ,- 1 ,0 ,0 ]
76+ queue = deque ([(characterX ,characterY )]) #queue 초기화
77+ field [characterX ][characterY ]= 0
78+ while queue :
79+ cur_x , cur_y = queue .popleft ()
80+ #인접 노드
81+ for idx in range (4 ):
82+ # 루트만 가능
83+ next_x ,next_y = cur_x + dx [idx ] , cur_y + dy [idx ]
84+ if field [next_x ][next_y ] == 1 : # 방문 x & 길
85+ field [next_x ][next_y ] = field [cur_x ][cur_y ] + 1
86+ # print(f"#{field[next_x][next_y]}")
87+ if next_x == itemX and next_y == itemY : # 목적지 도착 -> 결과 반환
88+ # print(f"#####{field[next_x][next_y]}")
89+ return field [next_x ][next_y ]// 2
90+ break
91+ queue .append ((next_x ,next_y ))
92+
93+ # print(f"#: {cur_x},{cur_y} => {field[cur_x][cur_y]}")
94+
95+ # print(f">{queue}")
96+ # print(f"##{field[next_x][next_y]}")
97+
98+
99+ return answer
0 commit comments