例题:百练2815 城堡问题

来源:互联网 发布:淘宝联盟能分享到qq群 编辑:程序博客网 时间:2024/05/16 01:14
#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;}

0 0
原创粉丝点击