반응형
https://www.acmicpc.net/problem/16946
16946번: 벽 부수고 이동하기 4
N×M의 행렬로 표현되는 맵이 있다. 맵에서 0은 이동할 수 있는 곳을 나타내고, 1은 이동할 수 없는 벽이 있는 곳을 나타낸다. 한 칸에서 다른 칸으로 이동하려면, 두 칸이 인접해야 한다. 두 칸이
www.acmicpc.net
#include <bits/stdc++.h>
using namespace std;
int n, m;
int arr[1001][1001];
vector<pair<int, int> > wall;
bool ch[1001][1001];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
int num[1001][1001];
int marked[1001*1001]; // cnt[mark] = 개수
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
for (int j = 0; j < m; j++) {
arr[i][j] = s[j]-'0';
if (arr[i][j]) wall.push_back({ i,j });
}
}
int mark = 1;
queue<pair<int, int> > Q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] == 0 && num[i][j] == 0) {
int cnt = 1;
Q.push({ i,j });
num[i][j] = mark;
while (!Q.empty()) {
int x = Q.front().first;
int y = Q.front().second;
Q.pop();
for (int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (nx < 0 || nx >= n || ny < 0 || ny >= m || num[nx][ny] || arr[nx][ny]) continue;
Q.push({ nx,ny });
cnt++;
num[nx][ny] = mark;
}
}
marked[mark] = cnt;
mark++;
}
}
}
for (int i = 0; i < wall.size(); i++) {
int x = wall[i].first;
int y = wall[i].second;
int wall_cnt = 1;
set<int> s;
for (int j = 0; j < 4; j++) {
int nx = x + dx[j];
int ny = y + dy[j];
if (nx < 0 || nx >= n || ny < 0 || ny >= m || arr[nx][ny] > 0) continue;
s.insert(num[nx][ny]);
}
for (auto k : s) {
wall_cnt += marked[k];
}
arr[x][y] = (wall_cnt % 10);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << arr[i][j];
}
cout << '\n';
}
return 0;
}
반응형
'Algorithm > problem' 카테고리의 다른 글
백준 1516번: 게임 개발 - 위상정렬 dp C++ 코드 (0) | 2022.02.24 |
---|---|
백준 2623번 : 음악프로그램 - 위상정렬 C++ 코드 (0) | 2022.02.24 |
백준 11495번 : 격자 0 만들기 - Network Flow C++ 코드 (0) | 2022.02.23 |
백준 5651번 : 완전 중요한 간선 - Network Flow C++ (0) | 2022.02.23 |
백준 2316번 : 도시 왕복하기 2 - Network Flow, 정점 분할 (0) | 2022.02.22 |