数据结构 深度优先 迷宫问题代码

来源:互联网 发布:梁朝伟 帅 知乎 编辑:程序博客网 时间:2024/04/28 20:46
Code:
  1. #include <iostream>  
  2. #include <cstring>  
  3. #include <list>  
  4. using namespace std;  
  5.   
  6. struct coor {  
  7.     int x, y;  
  8.     bool operator == (coor a)  
  9.     {  
  10.         if(a.x == x && a.y == y) return true;  
  11.         else return false;  
  12.     }  
  13.   
  14.     coor operator += (coor a)  
  15.     {  
  16.         x += a.x, y += a.y;  
  17.         return *this;  
  18.     }  
  19.   
  20.     coor operator -= (coor a)  
  21.     {  
  22.         x -= a.x, y -= a.y;  
  23.         return *this;  
  24.     }  
  25.   
  26.     bool pend(int n, int m)  
  27.     {  
  28.         if(x >= 0 && y >= 0 && x < m && y < n) return true;  
  29.         else return false;  
  30.     }  
  31. };  
  32.   
  33. int n, m;  
  34. int mat[20][20];  
  35. bool vis[20][20], ok = false;  
  36. coor op, ed;  
  37. list<coor> l;  
  38. const coor dir[4] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };  
  39. int all;  
  40.   
  41. void init()  
  42. {  
  43.     cout << "Input Row and Col: ";  
  44.     cin >> n >> m;  
  45.     cout << "Input the matrix:" << endl;  
  46.     for(int i = 0; i < n; i++)  
  47.         for(int j = 0; j < m; j++) cin >> mat[i][j];  
  48.   
  49.     cout << "Input the entrance coor: ";  
  50.     cin >> op.x >> op.y;  
  51.     cout << "Input the exit coor: ";  
  52.     cin >> ed.x >> ed.y;  
  53.   
  54.     cout << "Input if you wanna see all the solutions(0 / 1): ";  
  55.     cin >> all;  
  56.     l.push_back(op);  
  57.   
  58.     memset(vis, 0, sizeof(vis));  
  59. }  
  60.   
  61. void success()  
  62. {  
  63.     cout << endl;  
  64.     cout << "There'are total " << l.size() << " steps: " << endl;  
  65.   
  66.     for(list<coor>::iterator i = l.begin(); i != l.end(); i++)  
  67.         cout << " --> (" << i->x << ", " << i->y << ") <--" << endl;  
  68. }  
  69.   
  70. void dfs(coor now, coor ed)  
  71. {  
  72.     if(now == ed)  
  73.     {  
  74.         if(!all) ok = true;  
  75.         success();  
  76.     }  
  77.   
  78.     vis[now.y][now.x] = true;  
  79.     for(int i = 0; i < 4; i++)  
  80.     {  
  81.         now += dir[i];  
  82.         if(now.pend(n, m))  
  83.         {  
  84.             if(!mat[now.y][now.x] && !vis[now.y][now.x])  
  85.             {  
  86.                 l.push_back(now);  
  87.                 dfs(now, ed);  
  88.                 l.pop_back();  
  89.             }  
  90.   
  91.             if(ok) return;  
  92.         }  
  93.         now -= dir[i];  
  94.     }  
  95.     if(all) vis[now.y][now.x] = false;  
  96. }  
  97.   
  98. int main()  
  99. {  
  100.     init();  
  101.     dfs(op, ed);  
  102.   
  103.     return 0;  
  104. }  

 

 好吧,问题就是:读入一个迷宫,0是空地1是墙,然后DFS出出口。

原创粉丝点击