#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
int R, C;// 行列
int rooms[60][60];
int color[60][60];//房间是否染色过
int maxRoomArea = 0, roomNum = 0;
int roomArea;
struct Room{
int r, c;
Room(int rr, int cc):r(rr), c(cc) {} //初始化, 类似class的构造函数
};
/*//方法1:递归
void dfs(int x, int y) { // 递归
if(color[x][y]) return;
color[x][y] = 1;
++roomArea;
color[x][y] = roomNum;
if((rooms[x][y] & 1) == 0) dfs(x, y-1);//向西
if((rooms[x][y] & 2) == 0) dfs(x-1, y);//向北
if((rooms[x][y] & 4) == 0) dfs(x, y+1);//向东
if((rooms[x][y] & 8) == 0) dfs(x+1, y);//向南
}
*/
//方法2:用栈
void dfs(int r, int c) {
stack<Room> stk;
stk.push(Room(r, c)); // Room赋初值r,c, 返回一个结构体变量 真6! //居然还可以这么玩
while(!stk.empty()) {
Room rm = stk.top();
int i = rm.r;
int j = rm.c;
if(color[i][j]) stk.pop();//如果已经访问过了
else {
++ roomArea;
color[i][j] = roomNum;
if((rooms[i][j] & 1) == 0) stk.push(Room(i, j-1)); //西
if((rooms[i][j] & 2) == 0) stk.push(Room(i-1, j)); //北
if((rooms[i][j] & 4) == 0) stk.push(Room(i, j+1)); //东
if((rooms[i][j] & 8) == 0) stk.push(Room(i+1, j)); //南
}
}
}
int main() {
cin >> R >> C;
for(int i = 0; i < R; i++)
for(int j = 0; j < C; j++)
cin >> rooms[i][j];
memset(color, 0, sizeof(color));
for(int i = 0; i < R; i++)
for(int j = 0; j < C; j++)
if(!color[i][j]) {
++ roomNum;
roomArea = 0;
dfs(i, j);
maxRoomArea = max(roomArea, maxRoomArea);
}
cout << roomNum << endl;
cout << maxRoomArea << endl;
return 0;
}
例题:百练2815 城堡问题
最新推荐文章于 2022-07-07 11:08:46 发布