1. 程式人生 > >深搜1--城堡問題

深搜1--城堡問題

col 一個 -- clas set oms max image 結果

深搜1--城堡問題

一、心得

這個題目的棧實現可以看一看

也是很基礎的迷宮問題,也就是一個深搜

二、題目及分析

技術分享

技術分享

技術分享

技術分享

三、代碼及結果

遞歸

 1 #include <iostream>
 2 #include <stack>
 3 #include <cstring>
 4 using namespace std;
 5 int R,C; //行列數
 6 int rooms[60][60];
 7 int color[60][60]; //房間是否染色過的標記
 8 int maxRoomArea = 0, roomNum = 0;
 9 int roomArea;
10 void
Dfs(int i,int k) { 11 if( color[i][k] ) return; 12 ++roomArea; 13 color[i][k] = roomNum; 14 if( (rooms[i][k] & 1) == 0 ) Dfs(i,k-1); //向西走 15 if( (rooms[i][k] & 2) == 0 ) Dfs(i-1,k); //向北 16 if( (rooms[i][k] & 4) == 0 ) Dfs(i,k+1); //向東 17 if( (rooms[i][k] & 8) == 0
) Dfs(i+1,k); //向南 18 } 19 20 int main() { 21 freopen("in.txt","r",stdin); 22 cin >> R >> C; 23 for( int i = 1;i <= R;++i) 24 for ( int k = 1;k <= C; ++k) 25 cin >> rooms[i][k]; 26 memset(color,0,sizeof(color)); 27 for( int i = 1;i <= R; ++i)
28 for( int k = 1; k <= C; ++ k) { 29 if( !color[i][k] ) { 30 ++ roomNum ; roomArea = 0; 31 Dfs(i,k); 32 maxRoomArea =max(roomArea,maxRoomArea); 33 } 34 } 35 cout << roomNum << endl; 36 cout << maxRoomArea << endl; 37 }

技術分享

棧實現

 1 #include <iostream>
 2 #include <stack>
 3 #include <cstring>
 4 using namespace std;
 5 int R,C; //行列數
 6 int rooms[60][60];
 7 int color[60][60]; //房間是否染色過的標記
 8 int maxRoomArea = 0, roomNum = 0;
 9 int roomArea;
10 struct Room { int r,c; Room(int rr,int cc):r(rr),c(cc) { } };//構造函數用來初始化,
11 void Dfs(int r,int c) { //不用遞歸,用棧解決,程序其他部分不變
12     stack<Room> stk;
13     stk.push(Room(r,c));
14     while ( !stk.empty() ) {
15         Room rm = stk.top();
16         int i = rm.r; int k = rm.c;
17         if( color[i][k]) stk.pop();
18         else {
19             ++ roomArea;
20             color [i][k] = roomNum;
21             if((rooms[i][k]&1)==0) stk.push(Room(i,k-1));//西
22             if((rooms[i][k]&2)==0) stk.push(Room(i-1,k));//
23             if((rooms[i][k]&4) == 0) stk.push(Room(i,k+1));//
24             if((rooms[i][k]&8) == 0) stk.push(Room(i+1,k)); //
25         }
26     }
27 }
28 
29 int main() {
30     freopen("in.txt","r",stdin); 
31     cin >> R >> C;
32     for( int i = 1;i <= R;++i)
33         for ( int k = 1;k <= C; ++k)
34             cin >> rooms[i][k];
35     memset(color,0,sizeof(color));
36     for( int i = 1;i <= R; ++i)
37         for( int k = 1; k <= C; ++ k) {
38             if( !color[i][k] ) {
39                 ++ roomNum ; roomArea = 0;
40                 Dfs(i,k);
41                 maxRoomArea =max(roomArea,maxRoomArea);
42             }
43         }
44     cout << roomNum << endl;
45     cout << maxRoomArea << endl;
46 }

技術分享

深搜1--城堡問題