Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <sstream>
- #include <string>
- using namespace std;
- long long R, C;
- vector<vector<char> > maze;
- vector<vector<long long> > memoization;
- vector<pair<long long, long long> > visited;
- long long findPath(long long x, long long y);
- long long min(long long a, long long b);
- void tracepath();
- void dispmaze();
- int main(int argc, char** argv) {
- long long startx, starty;
- string s;
- getline(cin, s);
- stringstream ss(s);
- ss >> R >> C;
- //read input
- for (long long i = 0; i < R; i++) {
- vector<char> mazetmp;
- vector<long long> memoitmp;
- getline(cin, s);
- for (long long j = 0; j < C; j++) {
- mazetmp.push_back(s[j]);
- memoitmp.push_back(-1);
- if (s[j] == 'S') {
- startx = i;
- starty = j;
- }
- }
- maze.push_back(mazetmp);
- memoization.push_back(memoitmp);
- }
- //recurse
- long long ans = findPath(startx, starty);
- maze[startx][starty] = 'S';
- //display answer
- if (ans <= 0) {
- cout << "No Path" << "\n";
- } else {
- dispmaze();
- }
- }
- long long findPath(long long x, long long y) {
- if (x < 0 || y < 0) return -1000000;
- if (x >= R || y >= C) return -1000000;
- if (maze[x][y] == '#') return -1000000;
- if (maze[x][y] == 'E') return 0;
- if (memoization[x][y] != -1) {
- visited.push_back(pair<long long, long long>(x, y));
- return memoization[x][y];
- }
- maze[x][y] = '#';
- long long up, down, left, right;
- up = findPath(x - 1, y) + 1;
- down = findPath(x + 1, y) + 1;
- left = findPath(x, y - 1) + 1;
- right = findPath(x, y + 1) + 1;
- maze[x][y] = ' ';
- long long ans = min(min(up, down), min(left, right));
- memoization[x][y] = ans;
- if (ans > 0) visited.push_back(pair<long long, long long>(x, y));
- return ans;
- }
- long long min(long long a, long long b) {
- if (a <= 0) return b;
- if (b <= 0) return a;
- if (a < b) return a;
- return b;
- }
- void dispmaze() {
- tracepath();
- for (long long i = 0; i < R; i++) {
- for (long long j = 0; j < C; j++) {
- cout << maze[i][j];
- }
- cout << "\n";
- }
- }
- void tracepath() {
- for (long long i = 0; i < visited.size() - 1; i++) {
- maze[visited[i].first][visited[i].second] = '*';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement