Created
August 25, 2018 13:55
-
-
Save skyzh/5388d1375dff3b0cc397dacf51065073 to your computer and use it in GitHub Desktop.
Find path of maze
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <queue> | |
#include <vector> | |
using namespace std; | |
struct queue_item { | |
int x, y; | |
int step; | |
int prev; | |
}; | |
const int MAZE_N = 10; | |
const int MAZE_BLOCK = 1; | |
const int MAZE_FLOOR = 0; | |
const int MAZE[MAZE_N][MAZE_N] = { | |
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, | |
1, 0, 0, 0, 0, 0, 0, 0, 0, 1, | |
1, 1, 1, 1, 1, 1, 1, 1, 0, 1, | |
1, 0, 0, 0, 0, 0, 0, 0, 0, 1, | |
1, 0, 1, 1, 1, 0, 1, 1, 1, 1, | |
1, 0, 0, 0, 0, 0, 0, 0, 0, 1, | |
1, 1, 1, 1, 1, 1, 1, 1, 0, 1, | |
1, 0, 0, 0, 0, 0, 0, 0, 0, 1, | |
1, 0, 1, 1, 1, 0, 1, 1, 1, 1, | |
1, 0, 0, 0, 0, 0, 0, 0, 0, 1 | |
}; | |
const int MAZE_DIRECTION[4][2] = { | |
{0, 1}, {1, 0}, {0, -1}, {-1, 0} | |
}; | |
int bfs(int s_x, int s_y, int e_x, int e_y) { | |
vector <queue_item> maze_queue; | |
bool visited[MAZE_N][MAZE_N] = { 0 }; | |
queue_item front, current; | |
int cur_item = 0; | |
front.x = s_x; front.y = s_y; | |
front.step = 0; front.prev = -1; | |
maze_queue.push_back(front); | |
while (cur_item < maze_queue.size()) { | |
front = maze_queue[cur_item]; | |
++front.step; | |
front.prev = cur_item++; | |
if (front.x == e_x && front.y == e_y) { | |
for (int cur = cur_item; cur != -1; cur = maze_queue[cur].prev) { | |
queue_item &item = maze_queue[cur]; | |
cout << "(" << item.x << ", " << item.y << ")" << (cur == 0 ? "" : " <- "); | |
} | |
cout << endl; | |
return 0; | |
} | |
for (int i = 0; i < 4; i++) { | |
current = front; | |
current.x += MAZE_DIRECTION[i][0]; | |
current.y += MAZE_DIRECTION[i][1]; | |
if (current.x >= 0 && current.y >= 0 && current.x < MAZE_N && current.y < MAZE_N) { | |
if (MAZE[current.x][current.y] == MAZE_FLOOR) { | |
if (!visited[current.x][current.y]) { | |
visited[current.x][current.y] = true; | |
maze_queue.push_back(current); | |
} | |
} | |
} | |
} | |
} | |
cout << "NO SOLUTION" << endl; | |
return -1; | |
} | |
int main() { | |
bfs(1, 1, MAZE_N - 1, MAZE_N - 2); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment