-
프로그래머스 / 리코쳇 로봇코딩 테스트/Level 2 2023. 3. 17. 16:06반응형
https://school.programmers.co.kr/learn/courses/30/lessons/169199
주의할 점.
목표도 통과해 버린다. 목표에 멈출 수 있어야 성공~!파이썬
def solution(board): que = [] for x, row in enumerate(board): for y, each in enumerate(row): if each == '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
코틀린
class Solution { fun solution(board: Array<String>): Int { val que = ArrayDeque<Triple<Int, Int, Int>>() for (i in board.indices) { for (j in board[0].indices) { if (board[i][j] == 'R') que.add(Triple(i, j, 0)) } } val visited = mutableSetOf<Pair<Int, Int>>() val diffs = arrayOf(0 to 1, 0 to -1, 1 to 0, -1 to 0) while (que.isNotEmpty()) { val (x, y, length) = que.removeFirst() if (x to y in visited) continue if (board[x][y] == 'G') return length visited.add(x to y) for ((diffX, diffY) in diffs) { var (nowX, nowY) = x to y while (true) { val (nextX, nextY) = (nowX + diffX) to (nowY + diffY) if (0 <= nextX && nextX < board.size && 0 <= nextY && nextY < board[0].length && board[nextX][nextY] != 'D' ) { nowX = nextX nowY = nextY continue } que.add(Triple(nowX, nowY, length + 1)) break } } } return -1 } }
반응형