Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- #include <stack>
- using namespace std;
- struct Node
- {
- int x, y;
- int distance;
- Node() {}
- Node(int _x, int _y, int _distance) : x(_x), y(_y), distance(_distance) { }
- };
- int main()
- {
- http://www.stackoverflow.com/
- const unsigned int width = 5, height = 5;
- bool maze[width][height] = {
- { 0, 0, 0, 0, 0 },
- { 1, 1, 0, 1, 0 },
- { 0, 0, 0, 1, 0 },
- { 0, 1, 1, 1, 1 },
- { 0, 0, 0, 0, 0 }
- };
- bool visited[width][height];
- memset(visited, 0, sizeof(visited));
- stack<Node> s;
- s.push(Node(0, 0, 0)); // start at (0, 0), with a distance of 0
- int finalDistance = -1;
- while (!s.empty())
- {
- Node p = s.top();
- s.pop();
- if (p.x == width - 1 && p.y == height - 1) {
- finalDistance = p.distance;
- break;
- }
- if (visited[p.x][p.y]) continue;
- visited[p.x][p.y] = 1;
- if (p.x < width - 1 && maze[p.x + 1][p.y] == 0) s.push(Node(p.x + 1, p.y, p.distance + 1));
- if (p.x > 0 && maze[p.x - 1][p.y] == 0) s.push(Node(p.x - 1, p.y, p.distance + 1));
- if (p.y < height - 1 && maze[p.x][p.y + 1] == 0) s.push(Node(p.x, p.y + 1, p.distance + 1));
- if (p.y > 0 && maze[p.x][p.y - 1] == 0) s.push(Node(p.x, p.y - 1, p.distance + 1));
- }
- if (finalDistance == -1) cout << "No solution." << endl;
- else cout << "Distance: " << finalDistance << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement