http://ybt.ssoier.cn:8088/problem_show.php?pid=1250
此题目难点:
1.利用二进制的与运算判断与隔壁房间是否有墙,从而求出下一步的方向
2.与运算的优先性
3.代码的调试
1 #include<bits/stdc++.h> 2 using namespace std; 3 int m, n; 4 int a[60][60]; 5 bool vis[60][60]; 6 struct node{ 7 int x, y; 8 }; 9 node que[3600]; 10 int f, r; 11 int fx, fy;//用于获取队首信息,设置成全局变量方便多个函数间使用 12 int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};//本质上仍然是上下左右移动 13 14 int pr(){//测试搜索过程,用于52处行 15 for(int i=0; i<m; i++){ 16 for(int j=0; j<n; j++) 17 cout<<vis[i][j]<<" "; 18 cout<<endl; 19 } 20 21 } 22 int que_push(int i){ 23 int nx, ny; 24 int p=0;//用于入队计数并返回 25 nx=fx+dir[i][0]; 26 ny=fy+dir[i][1]; 27 if(nx>=0 && nx<m && ny>=0 && ny<n && vis[nx][ny]==0){ 28 p++;//有入队就加1,用于返回 29 vis[nx][ny]=1; 30 r++; 31 que[r].x=nx; 32 que[r].y=ny; 33 } 34 return p; 35 } 36 37 int bfs(int x, int y){ 38 int ret=0; 39 f=r=1; 40 que[r].x=x; que[r].y=y; vis[x][y]=1; ret++;//初始值入队 41 while(f<=r){ 42 fx=que[f].x, fy=que[f].y;//获取队首信息 43 int t=a[fx][fy];//注意二进制与运算一定要注意优先级(多加括号) 44 if((t&1)==0) //此题难点,通过二进制与运算识别是否有墙,转化为方向的移动 45 ret+=que_push(2);//向西 (左) 46 if((t&2)==0) 47 ret+=que_push(0);//向北 (上) 48 if((t&4)==0) 49 ret+=que_push(3);//向东(右) 50 if((t&8)==0) 51 ret+=que_push(1);//向南(下) 52 //pr(); 53 f++; 54 } 55 return ret; //返回入队个数 56 } 57 int cnt_room, max_room; 58 int main() 59 { 60 cin>>m>>n; 61 for(int i=0; i<m; i++) 62 for(int j=0; j<n; j++) 63 cin>>a[i][j]; 64 65 for(int i=0; i<m; i++) 66 for(int j=0; j<n; j++) 67 if(vis[i][j]==0){//注意此处如何判断 68 cnt_room++; 69 max_room=max(bfs(i, j), max_room);//求最大值 70 } 71 cout<<cnt_room<<endl<<max_room; 72 return 0; 73 }
另外此题仍然可以用DFS来写