백준 알고리즘(C++)

백준 3197번 백조의 호수 ( C++ )

coding232624 2024. 8. 18. 11:37

문제

https://www.acmicpc.net/problem/3197

 

해설

백조가 있는 곳에서 부터 얼음이 녹는것이 아닌 물이 있는곳 모든 곳에서 부터 얼음이 녹는것이 포인트

그렇기 때문에 얼음이 녹는것과 백조가 이동하는것을 따로 관리해야한다.

또한 백조가 있는곳은 물 위이기 때문에 백조가 있는곳도 물으로 처리해야 한다.

 

코드

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
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <bits/stdc++.h>
using namespace std;
 
int r, c, ret, startX, startY, x, y;
string line;
char mp[1504][1504];
int visited[1504][1504];
int dy[4= {-1010};
int dx[4= {010-1};
queue<pair<intint>> swan, swanTemp, melt, meltTemp;
 
void Qclear(queue<pair<intint>> &q)
{
  queue<pair<intint>> empty;
  swap(q, empty);
}
 
bool move_swan()
{
  while (swan.size())
  {
    tie(y, x) = swan.front();
    swan.pop();
    for (int i = 0; i < 4; i++)
    {
      int ny = y + dy[i];
      int nx = x + dx[i];
      if (ny < 0 || ny >= r || nx < 0 || nx >= c || visited[ny][nx] == 1)
        continue;
      visited[ny][nx] = 1;
      if (mp[ny][nx] == '.')
        swan.push({ny, nx});
      else if (mp[ny][nx] == 'L')
        return false;
      else
        swanTemp.push({ny, nx});
    }
  }
  return true;
}
 
void melting()
{
  while (melt.size())
  {
    tie(y, x) = melt.front();
    melt.pop();
    for (int i = 0; i < 4; i++)
    {
      int ny = y + dy[i];
      int nx = x + dx[i];
      if (ny < 0 || ny >= r || nx < 0 || nx >= c || visited[ny][nx] == 1)
        continue;
      if (mp[ny][nx] == 'X')
      {
        mp[ny][nx] = '.';
        meltTemp.push({ny, nx});
      }
    }
  }
}
 
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
 
  cin >> r >> c;
  for (int i = 0; i < r; i++)
  {
    cin >> line;
    for (int j = 0; j < c; j++)
    {
      mp[i][j] = line[j];
      if (mp[i][j] == 'L')
      {
        startY = i;
        startX = j;
        melt.push({i, j});
      }
      else if (mp[i][j] == '.')
      {
        melt.push({i, j});
      }
    }
  }
  swan.push({startY, startX});
  visited[startY][startX] = 1;
 
  while (move_swan())
  {
    melting();
    swan = swanTemp;
    melt = meltTemp;
    Qclear(swanTemp);
    Qclear(meltTemp);
    ret++;
  }
 
  cout << ret;
}
cs