문제 링크입니다: https://www.acmicpc.net/problem/1981
1981번: 배열에서 이동
문제 n×n짜리의 배열이 하나 있다. 이 배열의 (1, 1)에서 (n, n)까지 이동하려고 한다. 이동할 때는 상, 하, 좌, 우의 네 인접한 칸으로만 이동할 수 있다. 이와 같이 이동하다 보면, 배열에서 몇 개의 수를 거쳐서 이동하게 된다. 이동하기 위해 거쳐 간 수들 중 최댓값과 최솟값의 차이가 가장 작아지는 경우를 구하는 프로그램을 작성하시오. 입력 첫째 줄에 n(2≤n≤100)이 주어진다. 다음 n개의 줄에는 배열이 주어진다. 배열의 각 수는 0보
www.acmicpc.net
백준 2842번 집배원 한상덕(https://jaimemin.tistory.com/1279)과 유사하지만 조금 더 난이도가 쉬운 문제였습니다.
이차원 배열에 등장하는 모든 숫자들을 정렬된 상태로 각각 하나씩 가지고 있는 벡터 v가 이 문제의 핵심이였습니다.
low와 high를 초기에 0으로 두고 시뮬레이션을 통해 결과값을 계속 갱신해나가면 됩니다.
조건이 성립할 경우 low를 증가시키고 조건이 성립하지 않는 경우 high를 증가시킵니다.
조건이 성립하지 않고 더 이상 high를 증가시키지 못할 경우 반복문을 빠져나오면 되는 문제였습니다.
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 <vector> | |
#include <queue> | |
#include <algorithm> | |
#include <cstring> | |
using namespace std; | |
const int MAX = 100; | |
const int INF = 987654321; | |
typedef struct | |
{ | |
int y, x; | |
}Dir; | |
Dir moveDir[4] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} }; | |
int N; | |
int graph[MAX][MAX]; | |
bool visited[MAX][MAX]; | |
int result; | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
cin >> N; | |
vector<int> v; | |
for (int i = 0; i < N; i++) | |
{ | |
for (int j = 0; j < N; j++) | |
{ | |
cin >> graph[i][j]; | |
v.push_back(graph[i][j]); | |
} | |
} | |
sort(v.begin(), v.end()); | |
v.erase(unique(v.begin(), v.end()), v.end()); | |
result = INF; | |
int low = 0, high = 0; | |
while (low < v.size()) | |
{ | |
memset(visited, false, sizeof(visited)); | |
queue<pair<int, int>> q; | |
if (v[low] <= graph[0][0] && v[high] >= graph[0][0]) | |
{ | |
visited[0][0] = true; | |
q.push({ 0, 0 }); | |
} | |
while (!q.empty()) | |
{ | |
int y = q.front().first; | |
int x = q.front().second; | |
q.pop(); | |
for (int k = 0; k < 4; k++) | |
{ | |
int nextY = y + moveDir[k].y; | |
int nextX = x + moveDir[k].x; | |
if (nextY < 0 || nextY >= N || nextX < 0 || nextX >= N) | |
{ | |
continue; | |
} | |
if (visited[nextY][nextX]) | |
{ | |
continue; | |
} | |
if (v[low] <= graph[nextY][nextX] && v[high] >= graph[nextY][nextX]) | |
{ | |
visited[nextY][nextX] = true; | |
q.push({ nextY, nextX }); | |
} | |
} | |
} | |
if (visited[N - 1][N - 1]) | |
{ | |
result = min(result, v[high] - v[low]); | |
low++; | |
} | |
else if (high < v.size() - 1) | |
{ | |
high++; | |
} | |
else | |
{ | |
break; | |
} | |
} | |
cout << result << "\n"; | |
return 0; | |
} |


개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 7785번 회사에 있는 사람 (0) | 2019.10.21 |
---|---|
백준 6087번 레이저 통신 (0) | 2019.10.13 |
백준 2957번 이진 탐색 트리 (0) | 2019.10.08 |
백준 2933번 미네랄 (0) | 2019.10.07 |
백준 2186번 문자판 (7) | 2019.10.03 |