Search

리코쳇 로봇

입출력 예시

board
result
["...D..R", ".D.G...", "....D.D", "D....D.", "..D...."]
7
[".D.R", "....", ".G..", "...D"]
-1

나의 코드

from collections import deque import numpy as np def solution(board): board = [list(x) for x in board] board = np.array(board) m, n = board.shape print(m, n) def move(r, c, direction): ''' direction: {0: up, 1: down, 2: left, 3: right} ''' if direction == 0: # up while r >= 0 and board[r][c] != 'D': r -= 1 r += 1 elif direction == 1: # down while r < m and board[r][c] != 'D': r += 1 r -= 1 elif direction == 2: while c >= 0 and board[r][c] != 'D': c -= 1 c += 1 else: while c < n and board[r][c] != 'D': c += 1 c -= 1 return r, c def bfs(start, end): r, c = start[0].item(), start[1].item() gr, gc = end[0].item(), end[1].item() q = deque() visited = set() q.append((r, c, 0)) visited.add((r, c)) while len(q) > 0: r, c, k = q.popleft() if r == gr and c == gc: return k for i in [0, 1, 2, 3]: rnew, cnew = move(r, c, i) if (rnew, cnew) not in visited: q.append((rnew, cnew, k + 1)) visited.add((rnew, cnew)) return -1 start = np.where(board == 'R') end = np.where(board == 'G') # print(start, end) return bfs(start, end)
Python
복사

다른 풀이

def solution(board): que = [] for x, row in enumerate(board): for y, each in enumerate(row): if board[x][y] == 'R': que.append((x, y, 0)) visited = set() while que: x, y, length = que.pop(0) if (x, y) in visited: continue if board[x][y] == 'G': return length visited.add((x, y)) for diff_x, diff_y in ((0, 1), (0, -1), (1, 0), (-1, 0)): now_x, now_y = x, y while True: next_x, next_y = now_x + diff_x, now_y + diff_y if 0 <= next_x < len(board) and 0 <= next_y < len(board[0]) and board[next_x][next_y] != 'D': now_x, now_y = next_x, next_y continue que.append((now_x, now_y, length + 1)) break return -1
Python
복사

기억할 점 & 개선할 점

BFS 는 queue로 구현한다!
Array에서는 x축, y축 이 아니라 row, column 으로 이동하는게 안 헷갈린다.
while True:와 if 문 안의 continue를 잘 사용해보자.