You are given a map of a building made up of n×m squares, and each square is either a floor or a wall. Find how many rooms are in the building. A room is defined by a group of any number of adjacently connected floor squares, that is surrounded by walls. Input The first input line has two integers n and m: the height and width of the map. Then there are n lines each containing m characters describing the map. Each character is either . (floor) or # (wall). Output Print one integer, the number of rooms. Constraints 1≤n,m≤1000 Sample Input: 5 8 ######## #..#...# ####.#.# #..#...# ######## Output: 3
时间: 2024-04-16 13:27:03 浏览: 127
Sure! Here's a C++ code implementation that solves the problem:
cpp
#include <iostream>
#include <vector>
using namespace std;
int n, m;
vector<vector<char>> building;
vector<vector<bool>> visited;
// Define possible movements: up, down, left, right
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
// Function to perform DFS to find rooms
void explore(int x, int y) {
visited[x][y] = true;
// Explore all possible neighboring cells
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// Check if neighboring cell is within bounds and unvisited
if (nx >= 0 && nx < n && ny >= 0 && ny < m && building[nx][ny] == '.' && !visited[nx][ny]) {
explore(nx, ny);
}
}
}
int countRooms() {
int roomCount = 0;
// Initialize visited matrix
visited.assign(n, vector<bool>(m, false));
// Traverse through the building and count rooms
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (building[i][j] == '.' && !visited[i][j]) {
roomCount++;
explore(i, j);
}
}
}
return roomCount;
}
int main() {
cin >> n >> m;
// Read the building map
building.assign(n, vector<char>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> building[i][j];
}
}
int roomCount = countRooms();
cout << roomCount << endl;
return 0;
}
```
You can compile and run this code to get the desired output. Let me know if you have any further questions!
阅读全文