Search
Duplicate

리코쳇 로봇

문제 설명 및 제한사항

아이디어 및 해결 방법

코드

from collections import deque def move(board, r, c, direction): # 0: up # 1: right # 2: down # 3: left if direction == 0: while r >= 0 and board[r][c] != 'D': r -= 1 r += 1 elif direction == 1: while c < len(board[0]) and board[r][c] != 'D': c += 1 c -= 1 elif direction == 2: while r < len(board) and board[r][c] != 'D': r += 1 r -= 1 else: while c >= 0 and board[r][c] != 'D': c -= 1 c += 1 return r, c def bfs(board, r, c, gr, gc): q = deque() visited = set() q.append((r, c, 0)) visited.add((r, c)) while len(q) > 0: r, c, m = q.popleft() if r == gr and c == gc: return m for direction in [0, 1, 2, 3]: rnew, cnew = move(board, r, c, direction) if (rnew, cnew) not in visited: q.append((rnew, cnew, m + 1)) visited.add((rnew, cnew)) return -1 def solution(board): found = False for r, row in enumerate(board): for c, char in enumerate(row): if char == 'R': found = True break if found: break found = False for gr, row in enumerate(board): for gc, char in enumerate(row): if char == 'G': found = True break if found: break print(r, c, gr, gc) answer = bfs(board, r, c, gr, gc) return answer
Python
복사

출처

프로그래머스 코딩테스트 연습 https://school.programmers.co.kr/learn/challenges