kuangbin專題 專題一 簡單搜索 迷宮問題 POJ - 3984

 

題目連接:https://vjudge.net/problem/POJ-3984

這個題目,emm,上代碼,看的估計應該是剛開始接觸搜索的,我帶點註釋,你能慢慢理解。node


 

  1 #include <iostream>
  2 #include <cstring>
  3 #include<vector>
  4 #include<string>
  5 #include <cmath>
  6 #include <map>
  7 #include <queue>
  8 #include <algorithm>
  9 using namespace std;
 10 
 11 #define inf (1LL << 31) - 1
 12 #define rep(i,j,k) for(int i = (j); i <= (k); i++)
 13 #define rep__(i,j,k) for(int i = (j); i < (k); i++)
 14 #define per(i,j,k) for(int i = (j); i >= (k); i--)
 15 #define per__(i,j,k) for(int i = (j); i > (k); i--)
 16 
 17 const int N = 10;
 18 int mv_x[] = { 0, 0, -1, 1 };   //(1)
 19 int mv_y[] = { 1, -1, 0, 0 };   //(2)       (1) + (2) 能夠表示人的上下左右移動
 20 char mp[N][N];  //地圖
 21 bool vis[N][N];  //有沒有訪問過了
 22 
 23 struct node{
 24     int x, y;
 25     vector<string> vec;
 26     node(){}
 27     node(int a, int b){
 28         x = a;
 29         y = b;
 30     }
 31 };
 32 
 33 inline void input(){
 34 
 35     rep__(i, 0, 5) rep__(j, 0, 5) cin >> mp[i][j];
 36 }
 37 
 38 //檢查有無越界的函數
 39 inline bool check(int x, int y){
 40     return x >= 0 && x <= 4 && y >= 0 && y <= 4;
 41 }
 42 
 43 void fun(string& p){
 44     cout << p << endl;
 45 }
 46 
 47 void work(){
 48     
 49     //開始的處理,起點標記
 50     vis[0][0] = true;
 51     node T(0, 0);
 52     T.vec.push_back("(0, 0)");
 53 
 54     queue<node> que;
 55     que.push(T);
 56 
 57     while (!que.empty()){
 58 
 59         node tmp = que.front();
 60         que.pop();
 61 
 62         rep__(p, 0, 4){
 63 
 64             //人的移動
 65             int dx = tmp.x + mv_x[p];
 66             int dy = tmp.y + mv_y[p];
 67             
 68             //沒越界  是能夠走的   沒訪問過
 69             if (check(dx, dy) && mp[dx][dy] == '0' && !vis[dx][dy]){
 70                 vis[dx][dy] = true; //標記
 71 
 72                 node in = tmp;
 73                 in.x = dx;
 74                 in.y = dy;
 75                 string t = "(x, x)";
 76                 t[1] = '0' + dx;
 77                 t[4] = '0' + dy;
 78                 in.vec.push_back(t); //把新的點壓入
 79 
 80                 if (dx == 4 && dy == 4){ //遇到了出口,輸出路線
 81                     
 82                     for_each(in.vec.begin(), in.vec.end(), fun);
 83 
 84                     return;
 85                 }
 86                 que.push(in); //把新的狀態壓入隊列
 87             }
 88         }
 89     }
 90 }
 91 
 92 int main(){
 93 
 94     ios::sync_with_stdio(false);
 95     cin.tie(0);
 96 
 97     input();
 98     work();
 99 
100     return 0;
101 }
相關文章
相關標籤/搜索