To solve the problem of finding the shortest time for Bờm to escape the maze in both levels using Breadth-First Search (BFS), we'll approach each level separately due to their differing requirements.
Problem Breakdown
-
Level 1 (C = 1):
- Objective: Find the minimum time for Bờm to reach any key ('K') in the maze. Once a key is reached, the exit appears at that location, allowing Bờm to escape.
- Approach: Perform a BFS starting from Bờm's initial position and stop when the first key is reached. The number of steps taken to reach this key is the minimum time required.
-
Level 2 (C = 2):
- Objective: Bờm must collect both keys ('K') and then reach the exit door ('C') to escape.
- Approach: Implement a BFS that tracks the collection of keys using a bitmask. The state in the BFS will include Bờm's current position and the keys collected so far. The BFS will continue until Bờm has collected both keys and reached the exit door.
Implementation Details
-
Grid Representation:
- The maze is represented as a 2D grid with
N rows and M columns.
- Different characters represent different entities:
'B' - Bờm's starting position.
'#' - Obstacles that Bờm cannot pass through.
'K' - Keys that Bờm needs to collect.
'.' - Safe cells that Bờm can move through.
'C' - The exit door (only present in Level 2).
-
BFS Implementation:
- For Level 1:
- Use a standard BFS to find the shortest path from Bờm's starting position to any key.
- For Level 2:
- Use an extended BFS where each state includes Bờm's position and a bitmask representing the keys collected.
- The bitmask helps in tracking whether Bờm has collected the required keys.
- The BFS continues until Bờm has collected both keys and reached the exit.
-
Edge Cases:
- Ensure that the maze constraints are respected (e.g., Bờm cannot move outside the grid or through obstacles).
- Guarantee that the maze always allows Bờm to escape as per the problem statement.
C++ Solution
Below is the C++ implementation that adheres to the above approach. The program reads from TROCHOI.INP and writes the result to TROCHOI.OUT.
#include <bits/stdc++.h>
using namespace std;
// Directions: up, down, left, right
const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};
// Structure to represent state for BFS in C=2
struct State {
int x;
int y;
int k_mask;
};
int main(){
// Open input and output files
freopen("TROCHOI.INP", "r", stdin);
freopen("TROCHOI.OUT", "w", stdout);
int N, M, C;
cin >> N >> M >> C;
vector<string> grid(N);
for(int i=0;i<N;i++) {
cin >> grid[i];
}
// Find positions of B, K's, and C
int start_x = -1, start_y = -1;
vector<pair<int, int>> keys; // For C=2, need exactly 2 keys
int exit_x = -1, exit_y = -1;
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(grid[i][j] == 'B'){
start_x = i;
start_y = j;
}
else if(grid[i][j] == 'K'){
keys.emplace_back(i, j);
}
else if(grid[i][j] == 'C'){
exit_x = i;
exit_y = j;
}
}
}
if(C == 1){
// Level 1: BFS to find the minimum distance to any 'K'
vector<vector<bool>> visited(N, vector<bool>(M, false));
queue<pair<int, int>> q;
q.emplace(start_x, start_y);
visited[start_x][start_y] = true;
int steps = 0;
bool found = false;
while(!q.empty() && !found){
int sz = q.size();
for(int i=0;i<sz;i++){
pair<int, int> current = q.front(); q.pop();
int x = current.first;
int y = current.second;
// Check if current cell is 'K'
if(grid[x][y] == 'K'){
cout << steps;
return 0;
}
// Move to adjacent cells
for(int dir=0; dir<4; dir++){
int nx = x + dx[dir];
int ny = y + dy[dir];
// Check boundaries
if(nx >=0 && nx < N && ny >=0 && ny < M){
if(!visited[nx][ny] && grid[nx][ny] != '#'){
visited[nx][ny] = true;
q.emplace(nx, ny);
}
}
}
}
steps++;
}
// According to the problem, it's guaranteed that Bờm can escape
}
else if(C == 2){
// Level 2: BFS with state (x, y, k_mask)
// Need exactly 2 keys
if(keys.size() != 2){
// According to problem, C=2 always has 2 keys
// But to be safe
// Handle error or proceed
}
// Assign each key an index: 0 and 1
pair<int, int> key1 = keys[0];
pair<int, int> key2 = keys[1];
// Initialize visited array: N x M x 4
// k_mask can be from 0 to 3
vector<vector<vector<bool>>> visited(N, vector<vector<bool>>(M, vector<bool>(4, false)));
queue<State> q;
State start_state = {start_x, start_y, 0};
q.push(start_state);
visited[start_x][start_y][0] = true;
int steps = 0;
bool found = false;
while(!q.empty() && !found){
int sz = q.size();
for(int i=0;i<sz;i++){
State current = q.front(); q.pop();
int x = current.x;
int y = current.y;
int mask = current.k_mask;
// Check if current cell is 'C' and mask is 3 (both keys collected)
if(x == exit_x && y == exit_y && mask == 3){
cout << steps;
return 0;
}
// Move to adjacent cells
for(int dir=0; dir<4; dir++){
int nx = x + dx[dir];
int ny = y + dy[dir];
// Check boundaries
if(nx >=0 && nx < N && ny >=0 && ny < M){
if(grid[nx][ny] != '#'){
int new_mask = mask;
// Check if this cell is one of the keys
if(nx == key1.first && ny == key1.second){
new_mask |= 1; // Set bit 0
}
if(nx == key2.first && ny == key2.second){
new_mask |= 2; // Set bit 1
}
// Check if already visited
if(!visited[nx][ny][new_mask]){
visited[nx][ny][new_mask] = true;
State new_state = {nx, ny, new_mask};
q.push(new_state);
// If the new cell is 'C' and both keys collected, we can return
if(nx == exit_x && ny == exit_y && new_mask == 3){
cout << (steps +1);
return 0;
}
}
}
}
}
}
steps++;
}
}
return 0;
}
Explanation of the Code
-
Input Handling:
- The program reads the maze dimensions (
N, M), the level (C), and the maze grid from the input file TROCHOI.INP.
- It identifies the positions of Bờm (
'B'), keys ('K'), and the exit door ('C').
-
Level 1 (C = 1) Implementation:
- A standard BFS is performed starting from Bờm's position.
- The BFS explores all possible directions (up, down, left, right) and marks cells as visited to avoid revisiting.
- The search stops as soon as a key is found, and the number of steps taken to reach this key is output.
-
Level 2 (C = 2) Implementation:
- An extended BFS is employed where each state includes Bờm's current position and a bitmask representing the keys collected.
- The bitmask (
k_mask) uses two bits to track the collection of the two keys:
- Bit 0 (
1) indicates the first key has been collected.
- Bit 1 (
2) indicates the second key has been collected.
- The BFS continues until Bờm has collected both keys (
k_mask == 3) and reaches the exit door ('C').
- The number of steps taken to achieve this is then output.
-
Output:
- The program writes the result to the output file
TROCHOI.OUT, indicating the minimum time required for Bờm to escape the maze based on the level.
Testing with Provided Examples
-
Example 1:
Input (TROCHOI.INP):
2 6 1
#B..#K
K....K
Output (TROCHOI.OUT):
2
-
Example 2:
Input (TROCHOI.INP):
3 5 2
K.C#.
..K.B
.....
Output (TROCHOI.OUT):
7
The provided code correctly handles both examples, ensuring accurate and efficient BFS implementations for both levels of the game.