Gold 3
23288번: 주사위 굴리기 2
크기가 N×M인 지도가 존재한다. 지도의 오른쪽은 동쪽, 위쪽은 북쪽이다. 지도의 좌표는 (r, c)로 나타내며, r는 북쪽으로부터 떨어진 칸의 개수, c는 서쪽으로부터 떨어진 칸의 개수이다. 가장 왼
www.acmicpc.net
문제 풀이
DFS + 구현 문제
1) 주어진 방향(처음엔 동쪽)으로 좌표를 이동시키고 범위를 벗어난 경우 반대방향으로 이동시킨다.
2) 이동한 칸의 점수를 획득한다.
3) 주사위 바닥면의 값과 이동한 칸의 값을 비교해 다음 진행할 방향을 정해준다.
이렇게 동작하는 solution함수를 짜줬고, dfs함수를 따로 빼서 점수를 계산할 수 있도록 해주었다.
코드
def dice_move(direction, dice):
dice[5], dice[4], dice[direction], dice[opp[direction]] = \
dice[direction], dice[opp[direction]], dice[4], dice[5]
def dfs(visited, pos_x, pos_y, num):
global count
for i in range(4):
nx = pos_x + mx[i]
ny = pos_y + my[i]
if 0 <= nx < n and 0 <= ny < m:
if visited[nx][ny] == 0 and board[nx][ny] == num:
visited[nx][ny] = 1
count += 1
dfs(visited, nx, ny, num)
def solution():
global count
answer = 0
x, y = 0, 0
direction = 0 # 처음 direction 은 동쪽
for _ in range(k):
nx = x + mx[direction]
ny = y + my[direction]
# 범위 밖을 벗어난 경우 반대방향으로 이동
if nx < 0 or nx >= n or ny < 0 or ny >= m:
direction = opp[direction]
nx = x + mx[direction]
ny = y + my[direction]
# 점수 계산
count = 1
x, y = nx, ny
visited = [[0] * m for _ in range(n)]
visited[x][y] = 1
dfs(visited, x, y, board[x][y])
visited[x][y] = 0
answer += (count * board[x][y])
dice_move(direction, dice)
# 방향 변경
if dice[-1] > board[x][y]:
direction = c_rotation[direction]
elif dice[-1] < board[x][y]:
direction = uc_rotation[direction]
print(answer)
n, m, k = map(int, input().split())
board = []
for _ in range(n):
board.append(list(map(int, input().split())))
# 초기 상태 주사위
dice = [3, 4, 2, 5, 1, 6]
mx = [0, 0, -1, 1]
my = [1, -1, 0, 0]
opp = [1, 0, 3, 2] # 반대 면에 해당하는 면
count = 0
# 회전을 위한 리스트
c_rotation = [3, 2, 0, 1]
uc_rotation = [2, 3, 1, 0]
solution()728x90
'Algorithm > Problem' 카테고리의 다른 글
| [Baekjoon] 15685번 : 드래곤 커브 - Python (0) | 2022.03.04 |
|---|---|
| [Baekjoon] 17142번 : 연구소 3 - Python (0) | 2022.02.25 |
| [Programmers] 여행 경로 - Java (0) | 2022.02.18 |
| [Programmers] 단어 변환 - Java (0) | 2022.02.18 |
| [Programmers] 네트워크 - Java (0) | 2022.02.18 |