-
백준(BOJ) 2169번 로봇 조종하기알고리즘 풀이/백준(Boj) 2019. 10. 27. 00:37
문제 : https://www.acmicpc.net/problem/2169
2169번: 로봇 조종하기
첫째 줄에 N, M(1≤N, M≤1,000)이 주어진다. 다음 N개의 줄에는 M개의 수로 배열이 주어진다. 배열의 각 수는 절댓값이 100을 넘지 않는 정수이다. 이 값은 그 지역의 가치를 나타낸다.
www.acmicpc.net
풀이 :
로봇은 왼쪽으로도 갈 수 있기 때문에 일반적인 메모이제이션 cache [y][x]는 최적의 값을 찾아주지 못한다. 따라서 cache
는 3가지 방향을 전부 다 잡아주어야 한다.
코드 ( C++ )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#include <iostream> #include <algorithm> #include <cstring> #include <string> using namespace std; int N, M; int mars[1001][1001]; int visited[1000][1000]; int cache[1001][1001][3]; const int dy[3] = { 1,0,0 }; const int dx[3] = { 0,1,-1 }; const int MINF = -1000000; int solve(int y, int x, int dir) { if (y == N - 1 && x == M-1) { return mars[y][x]; } int& ret = cache[y][x][dir]; if (ret != MINF) return ret; for (int i = 0; i < 3; ++i) { int ny = y + dy[i]; int nx = x + dx[i]; if (!(0 <= ny && ny < N && 0 <= nx && nx < M)) continue; if (visited[ny][nx]) continue; visited[ny][nx] = true; ret = max(ret, solve(ny, nx, i) + mars[y][x]); visited[ny][nx] = false; } return ret; } int main() { cin >> N >> M; for (int i = 0; i < N; ++i) for (int j = 0; j < M; ++j) { cin >> mars[i][j]; cache[i][j][0] = cache[i][j][1] = cache[i][j][2] = MINF; } visited[0][0] = true; cout << solve(0, 0,0) << "\n"; return 0; } '알고리즘 풀이 > 백준(Boj)' 카테고리의 다른 글
백준(BOJ) 3085번 사탕 게임 (0) 2019.10.27 백준(BOJ) 1937번 욕심쟁이 판다 (31) 2019.10.27 백준(BOJ) 14225번 부분수열의 합 (31) 2019.10.25 백준(BOJ) 2151번 거울 설치 (31) 2019.10.22 백준(BOJ) 2422번 한윤정이 이탈리아에 가서 아이스크림을 사먹는데 (31) 2019.10.18