#include #include #include #include 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 map, stack 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 map, int n, int m, vector > visited, stack 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 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 > visited(row, vector(col, false)); stack nodes; transverse(map, x, y, visited, nodes); } int main(){ cin >> col >> row; char ch; vector 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; }