# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
1253839 | shawnchang51 | Maze (JOI23_ho_t3) | C++17 | 0 ms | 0 KiB |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
```
int R, C, N;
cin >> R >> C >> N;
int Sr, Sc, Gr, Gc;
cin >> Sr >> Sc >> Gr >> Gc;
Sr--; Sc--; Gr--; Gc--; // Convert to 0-indexed
vector<string> grid(R);
for (int i = 0; i < R; i++) {
cin >> grid[i];
}
// BFS with distance representing minimum stamp operations needed
vector<vector<int>> dist(R, vector<int>(C, -1));
queue<pair<int, int>> q;
// Start BFS from the starting position
dist[Sr][Sc] = 0;
q.push({Sr, Sc});
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
// First, find all cells reachable with 0 operations (just white cell traversal)
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
for (int dir = 0; dir < 4; dir++) {
int nx = x + dx[dir];
int ny = y + dy[dir];
if (nx >= 0 && nx < R && ny >= 0 && ny < C &&
dist[nx][ny] == -1 && grid[nx][ny] == '.') {
dist[nx][ny] = 0;
q.push({nx, ny});
}
}
}
if (dist[Gr][Gc] == 0) {
cout << 0 << endl;
return 0;
}
// Now use BFS for stamp operations
for (int ops = 1; ops <= 50; ops++) {
vector<pair<int, int>> newCells;
// Try all possible stamp positions
for (int a = 0; a <= R - N; a++) {
for (int b = 0; b <= C - N; b++) {
// Check if this stamp connects to any cell reachable with ops-1 operations
bool connects = false;
for (int i = a; i < a + N && !connects; i++) {
for (int j = b; j < b + N && !connects; j++) {
if (dist[i][j] != -1 && dist[i][j] < ops) {
connects = true;
}
}
}
if (connects) {
// This stamp can be used, mark all cells in stamp region as reachable with ops operations
for (int i = a; i < a + N; i++) {
for (int j = b; j < b + N; j++) {
if (dist[i][j] == -1) {
dist[i][j] = ops;
newCells.push_back({i, j});
}
}
}
}
}
}
// From newly reachable cells, do BFS to find other reachable white cells
queue<pair<int, int>> bfsQ;
for (auto& cell : newCells) {
bfsQ.push(cell);
}
while (!bfsQ.empty()) {
auto [x, y] = bfsQ.front();
bfsQ.pop();
for (int dir = 0; dir < 4; dir++) {
int nx = x + dx[dir];
int ny = y + dy[dir];
if (nx >= 0 && nx < R && ny >= 0 && ny < C &&
dist[nx][ny] == -1 && grid[nx][ny] == '.') {
dist[nx][ny] = ops;
bfsQ.push({nx, ny});
}
}
}
if (dist[Gr][Gc] == ops) {
cout << ops << endl;
return 0;
}
}
cout << dist[Gr][Gc] << endl;
return 0;
```
}