알고리즘
백준 1113번 수영장 만들기 C++
영춘권의달인
2022. 4. 14. 11:07
bfs를 돌면서 물을 채울 수 있다면 일단 job 큐에 넣어두고 마지막까지 탐색을 마쳤을 때 물이 새는 곳이 없다면
그때 job큐를 돌면서 물을 채워주는 방식으로 문제를 해결하였다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
using namespace std;
using ll = long long;
int n, m;
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
vector<vector<int>> board(50, vector<int>(50));
vector<vector<bool>> found(50, vector<bool>(50, false));
void RefreshFound() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
found[i][j] = false;
}
}
}
int bfs(int row, int col) {
RefreshFound();
found[row][col] = true;
queue<pair<int, int>> q;
queue<pair<int, int>> job;
q.push({ row,col });
bool isPossible = true;
int minWall = 10;
int maxHeight = 0;
int ret = 0;
while (!q.empty()) {
auto curr = q.front();
q.pop();
maxHeight = max(maxHeight, board[curr.first][curr.second]);
job.push({ curr.first,curr.second });
for (int i = 0; i < 4; i++) {
int nextRow = curr.first + dRow[i];
int nextCol = curr.second + dCol[i];
if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= m) {
isPossible = false;
break;
}
if (found[nextRow][nextCol]) continue;
if (board[nextRow][nextCol] > maxHeight) {
minWall = min(minWall, board[nextRow][nextCol]);
continue;
}
found[nextRow][nextCol] = true;
q.push({ nextRow,nextCol });
}
}
if (!isPossible) return ret;
while (!job.empty()) {
auto curr = job.front();
job.pop();
int water = minWall - board[curr.first][curr.second];
board[curr.first][curr.second] = minWall;
ret += water;
}
return ret;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
for (int j = 0; j < m; j++) {
board[i][j] = str[j] - '0';
}
}
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
sum += bfs(i, j);
}
}
cout << sum;
};