Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <stack>
- #include <algorithm>
- using namespace std;
- #define right 1
- #define down 2
- #define left 3
- #define up 4
- int row, col;
- struct Point{
- int x, y, direction;
- Point(int x, int y){
- this->x = x;
- this->y = y;
- direction = 1;
- }
- };
- void printSolution(vector <string> map, stack <Point> path){
- while(!path.empty()){
- Point point = path.top(); path.pop();
- if(map[point.x][point.y] != 'S' && map[point.x][point.y] != 'E')
- map[point.x][point.y] = '1';
- }
- for(int i = 0; i < row; i++){
- for(int j = 0; j < col; j++){
- cout << map[i][j] << " ";
- }
- }
- }
- void transverse(vector <string> map, int n, int m, vector <vector<bool>> visited, stack <Point> nodes){
- Point point(n, m);
- nodes.push(point);
- while(!nodes.empty()){
- Point temp = nodes.top();
- int dir = temp.direction;
- int x = temp.x, y = temp.y;
- temp.direction++;
- nodes.pop();
- nodes.push(temp);
- //cout << "X = " << x << " Y = " << y << endl;
- //cout << "Direction : " << dir << endl;
- if(map[x][y] == 'E')
- return printSolution(map, nodes);
- if(dir == right){
- if(map[x][y + 1] != '2' && !visited[x][y + 1]){
- Point p(x, y + 1);
- visited[x][y + 1] = true;
- nodes.push(p);
- //cout << "Right" << endl;
- }
- }
- else if(dir == down){
- if(map[x + 1][y] != '2' && !visited[x + 1][y]){
- Point p(x + 1, y);
- visited[x + 1][y] = true;
- nodes.push(p);
- //cout << "Bottom" << endl;
- }
- }
- else if(dir == left){
- if(map[x][y - 1] != '2' && !visited[x][y - 1]){
- Point p(x, y - 1);
- visited[x][y - 1] = true;
- nodes.push(p);
- //cout << "Left" << endl;
- }
- }
- else if(dir == up){
- if(map[x - 1][y] != '2' && !visited[x - 1][y]){
- Point p(x - 1, y);
- visited[x - 1][y] = true;
- nodes.push(p);
- //cout << "Up" << endl;
- }
- }
- else{
- visited[x][y] = false;
- nodes.pop();
- }
- }
- cout << "No solution found! End point not reachable!" << endl;
- }
- void solve(vector <string> map){
- int x = -1, y = -1;
- for(int i = 0; i < row && x == -1; i++){
- for(int j = 0; j < col; j++){
- if(map[i][j] == 'S'){
- x = i;
- y = j;
- break;
- }
- }
- }
- //cout << x << " " << y << endl;
- vector <vector<bool> > visited(row, vector<bool>(col, false));
- stack <Point> nodes;
- transverse(map, x, y, visited, nodes);
- }
- int main(){
- cin >> col >> row;
- char ch;
- vector <string> map;
- for(int i = 0; i < row; i++){
- string str = "";
- for(int j = 0; j < col; j++){
- cin >> ch;
- str += ch;
- }
- map.push_back(str);
- }
- solve(map);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement