코딩테스트 연습 - 블록 이동하기 | 프로그래머스 (programmers.co.kr)
코딩테스트 연습 - 블록 이동하기
[[0, 0, 0, 1, 1],[0, 0, 0, 1, 0],[0, 1, 0, 1, 1],[1, 1, 0, 0, 1],[0, 0, 0, 0, 0]] 7
programmers.co.kr
손쉽게 풀었다. 코딩 실력이 늘고 있는게 느껴지는구만
이 문제는 좌표에 유의해서 풀어야 한다.
from collections import deque
def solution(board):
N = len(board)
newboard = [[1] * (N+2) for _ in range(N+2)]
for i in range(N):
for j in range(N):
newboard[i+1][j+1] = board[i][j]
startpos = {(1,1),(1,2)}
q = deque()
q.append((startpos,0))
visited = []
answer = 0
while q:
position, distance = q.popleft()
if position in visited:
continue
else:
visited.append(position)
print(position)
position = list(position)
if (N,N) in position:
answer = distance
break
x1,y1 = position[0]
x2,y2 = position[1]
if y1==y2:
if newboard[x1][y1+1]==0 and newboard[x2][y2+1]==0:
q.append(({(x1,y1),(x1,y1+1)}, distance+1))
q.append(({(x2,y2),(x2,y2+1)}, distance+1))
if newboard[x1][y1-1]==0 and newboard[x2][y2-1]==0:
q.append(({(x1,y1),(x1,y1-1)}, distance+1))
q.append(({(x2,y2),(x2,y2-1)}, distance+1))
elif x1==x2:
if newboard[x1+1][y1]==0 and newboard[x2+1][y2]==0:
q.append(({(x1,y1),(x1+1,y1)}, distance+1))
q.append(({(x2,y2),(x2+1,y2)}, distance+1))
if newboard[x1-1][y1]==0 and newboard[x2-1][y2]==0:
q.append(({(x1,y1),(x1-1,y1)}, distance+1))
q.append(({(x2,y2),(x2-1,y2)}, distance+1))
dx = [0,0,-1,1]
dy = [1,-1,0,0]
for i in range(4):
newx1 = x1+dx[i]
newy1 = y1+dy[i]
newx2 = x2+dx[i]
newy2 = y2+dy[i]
if newboard[newx1][newy1]==0 and newboard[newx2][newy2]==0:
q.append( ({(newx1,newy1),(newx2,newy2)}, distance+1) )
return answer
'코딩 테스트 및 알고리즘 > 이것이 취업을 위한 코딩테스트다' 카테고리의 다른 글
Q8. 문자열 재정렬 (0) | 2022.03.31 |
---|---|
Q7. 럭키 스트레이트 (0) | 2022.03.30 |
Q21. 인구이동 (0) | 2022.03.29 |
Q20. 감시 피하기 (0) | 2022.03.28 |
Q19. 연산자 끼워 넣기 (삼성 기출) (0) | 2022.03.25 |