본문 바로가기
백준

백준 1981 배열에서 이동

by 콩순이냉장고 2021. 5. 20.

문제 URL : https://www.acmicpc.net/problem/1981

 

1981번: 배열에서 이동

n×n짜리의 배열이 하나 있다. 이 배열의 (1, 1)에서 (n, n)까지 이동하려고 한다. 이동할 때는 상, 하, 좌, 우의 네 인접한 칸으로만 이동할 수 있다. 이와 같이 이동하다 보면, 배열에서 몇 개의 수를

www.acmicpc.net

 

문제 접근법 : 

이분탐색을 이용한 bfs문제입니다. 

즉 최소구간을 1~부터 최소가되는 어느지점까지 완전탐색을 하는게 좋겠지만 시간초과가가 발생해버리니 lowerbound 탐색을 이용해야합니다. 

 

소스코드:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//By 콩순이냉장고
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include<queue>
#include <cstring>
using namespace std;
 
int dy[4= { -1,0,1,0 };
int dx[4= { 0,1,0,-1 };
int n;
int board[100][100];
int Max = 0;
int Min = 1e8;
int visit[100][100];
bool isrange(int y, int x) {
    return 0 <= y && y < n && 0 <= x && x < n;
}
void input() {
    cin >> n;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> board[i][j];
            Max = max(Max, board[i][j]);
            Min = min(Min, board[i][j]);
        }
    }
}
 
bool bfs(int small,int big) {
    if (!(small <= board[0][0&& board[0][0<= big))
        return false;
    memset(visit, 0sizeof(visit));
    queue<pair<intint>> q;
    q.push({ 0,0 });
    visit[0][0= 1;
    while (!q.empty()) {
        int y = q.front().first;
        int x = q.front().second;
        q.pop();
        if(y==n-1&&x==n-1)
            return true;
        for (int i = 0; i < 4; i++) {
            int ny = y + dy[i];
            int nx = x + dx[i];
            if (isrange(ny, nx) && visit[ny][nx] == 0) {
                if (small <= board[ny][nx] && board[ny][nx] <= big)
                {
                    q.push({ ny,nx });
                    visit[ny][nx] = 1;
                }
            }
        }
    }
    return false;
}
 
bool check(int mid) {
    for (int i = 0; i+mid <= 200; i++) {
        if (bfs(i, i + mid))
            return true;
    }
    return false;
}
void solve() {
    int left = 0;
    int right = Max;
    int res = Max - Min;
    while (left <= right) {
        int mid = (left + right) / 2;
        if (check(mid)) {
            res = min(mid, res);
            right = mid - 1;
        }
        else {
            left = mid + 1;
        }
    }
    cout << left << "\n";
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    input();
    solve();
}
 
cs

 

궁금한점 혹은 모르는점 어떤질문이든 환영입니다. 언제든지 댓글을 이용해주시길 바랍니다.

 

'백준' 카테고리의 다른 글

백준 3079 입국심사  (0) 2021.05.20
백준 16434 드래곤 앤 던전  (0) 2021.05.20
백준 2585 경비행기  (0) 2021.05.20
백준 8983 사냥꾼  (1) 2021.05.14
백준 20437 문자열 게임2  (0) 2021.05.05