본문 바로가기
SWEA

[SWEA] 10966 물놀이를 가자

by 콩순이냉장고 2021. 6. 21.

문제 URL : https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AXWXMZta-PsDFAST 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

문제접근법 : 육지에서 물이 가장가까운 거리를 찾는 문제입니다.

그렇지만 반대로 생각하면 물에서 육지로 갈때 가까운거리를 찾아 그거리들의 합을 계산하면되고

bfs를 이용한 dijkstra를 이용하면 답은 쉽게 찾을수 있습니다.

 

소스코드:

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
//By 콩순이냉장고
#include <algorithm>
#include <vector>
#include <queue>
#include <unordered_map>
#include <iostream>
#include <string>
 
using namespace std;
int dy[4= { -1,0,1,0 };
int dx[4= { 0,1,0,-1 };
int n, m;
char board[1000][1000];
vector<pair<intint>> water;
int dist[1000][1000];
void init() {
    water.clear();
}
void input() {
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> board[i][j];
            if (board[i][j] == 'W')
                water.push_back({ i,j });
        }
    }
}
 
bool isrange(int y, int x) {
    return 0 <= y && y < n && 0 <= x && x < m;
}
int dijkstra() {
  
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            dist[i][j] = 1e9;
    queue<pair<int,int>> q;
    for (int i = 0; i < water.size(); i++) {
        q.push({ water[i].first,water[i].second });
        dist[water[i].first][water[i].second] = 0;
    }
    while (!q.empty()) {
        int y = q.front().first;
        int x = q.front().second;
        q.pop();
        for (int i = 0; i < 4; i++) {
            int ny = y + dy[i];
            int nx = x + dx[i];
            if (isrange(ny, nx) && board[ny][nx] == 'L' && dist[ny][nx] > dist[y][x]+1) {
                dist[ny][nx] = dist[y][x] + 1;
                q.push({ ny,nx });
            }
        }
    }
    int sum = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (dist[i][j] != 1e9)
                sum += dist[i][j];
    return sum;
 
}
 
void solve() {
    cout << dijkstra() << "\n";
 
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("input.txt", "r", stdin);
    int test;
    cin >> test;
    for (int i = 1; i <= test; i++) {
        cout << "#" << i << " ";
        init();
        input();
        solve();
    }
}
 
cs

 

궁금한점 혹은 모르는점 어떤 지적이든 좋습니다. 댓글은 언제나 환영입니다.