




코딩테스트 연습 - 리코쳇 로봇 | 프로그래머스 스쿨 (programmers.co.kr)
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
나의 코드
from collections import deque
def solution(board):
answer = 9999
# 시작, 목표 좌표를 구하고, board_list를 만듬
R_point = []
G_point = []
board_list = []
for i in range(len(board)):
i_list=list(board[i])
if 'R' in i_list:
R_point=[i, i_list.index('R')]
if 'G' in i_list:
G_point=[i,i_list.index('G')]
board_list.append(i_list)
print(board_list)
#print(R_point)
#print(G_point)
# 방문체크 위한 리스트 생성
visit = []
for i in range(len(board_list)):
visit.append([0]*len(board_list[0]))
#print(visit)
queue = deque()
# queue 시작값( R의 행 좌표, R의 열 좌표, 이동한 횟수 )
queue.append([R_point[0], R_point[1], 0])
while queue:
x,y,c = queue.popleft()
# 이동한 좌표가 G(목표) 이면
# 이동한 최솟값을 answer로 치환하고 continue
if board_list[x][y]=='G':
answer = min(answer, c)
continue
# 아니면 방문체크하고 이동 계속
else:
visit[x][y]=1
# 상하좌우로 막히기 전까지 이동(while)
for move in [(1,0),(-1,0),(0,1),(0,-1)]:
new_x=x
new_y=y
while True:
update_new_x=new_x+move[0]
update_new_y=new_y+move[1]
if 0<=update_new_x<len(board_list) and 0<=update_new_y<len(board_list[0]) and (board_list[update_new_x][update_new_y]=='.' or board_list[update_new_x][update_new_y]=='G' or board_list[update_new_x][update_new_y]=='R'):
new_x=update_new_x
new_y=update_new_y
else:
break
# 이동한 좌표가 방문처리가 안된 곳이면 queue에 append 해준다
if visit[new_x][new_y]==0 and [new_x, new_y, c+1] not in queue:
queue.append([new_x, new_y, c+1])
#print(new_x,new_y)
# 도달할수 없는경우 1을 리턴
if answer==9999:
return -1
return answer'코딩테스트 파이썬 > 파이썬 프로그래머스 2단계' 카테고리의 다른 글
| Softeer 연습문제(2단계) - 전광판 (2) | 2024.06.25 |
|---|---|
| 디펜스 게임 (0) | 2024.04.18 |
| 하노이의 탑 (0) | 2024.02.15 |
| 점 찍기 (2) | 2023.11.24 |
| 테이블 해시 함수 (1) | 2023.11.23 |