Advertisement
jli

DFS/Stack

jli
Nov 29th, 2011
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. #include <stack>
  4.  
  5. using namespace std;
  6.  
  7. struct Node
  8. {
  9.     int x, y;
  10.     int distance;
  11.     Node() {}
  12.     Node(int _x, int _y, int _distance) : x(_x), y(_y), distance(_distance) { }
  13. };
  14.  
  15. int main()
  16. {
  17.     http://www.stackoverflow.com/
  18.  
  19.     const unsigned int width = 5, height = 5;
  20.  
  21.     bool maze[width][height] = {
  22.         { 0, 0, 0, 0, 0 },
  23.         { 1, 1, 0, 1, 0 },
  24.         { 0, 0, 0, 1, 0 },
  25.         { 0, 1, 1, 1, 1 },
  26.         { 0, 0, 0, 0, 0 }
  27.     };
  28.     bool visited[width][height];
  29.     memset(visited, 0, sizeof(visited));
  30.  
  31.     stack<Node> s;
  32.     s.push(Node(0, 0, 0)); // start at (0, 0), with a distance of 0
  33.  
  34.     int finalDistance = -1;
  35.     while (!s.empty())
  36.     {
  37.         Node p = s.top();
  38.         s.pop();
  39.         if (p.x == width - 1 && p.y == height - 1) {
  40.             finalDistance = p.distance;
  41.             break;
  42.         }
  43.         if (visited[p.x][p.y]) continue;
  44.         visited[p.x][p.y] = 1;
  45.         if (p.x < width - 1 && maze[p.x + 1][p.y] == 0) s.push(Node(p.x + 1, p.y, p.distance + 1));
  46.         if (p.x > 0 && maze[p.x - 1][p.y] == 0) s.push(Node(p.x - 1, p.y, p.distance + 1));
  47.         if (p.y < height - 1 && maze[p.x][p.y + 1] == 0) s.push(Node(p.x, p.y + 1, p.distance + 1));
  48.         if (p.y > 0 && maze[p.x][p.y - 1] == 0) s.push(Node(p.x, p.y - 1, p.distance + 1));
  49.     }
  50.  
  51.     if (finalDistance == -1) cout << "No solution." << endl;
  52.     else cout << "Distance: " << finalDistance << endl;
  53.     return 0;
  54. }
  55.  
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement