Input :
MX.....XB. ..X..X.X.. ...X.X.X.. .....X....Output : found :)
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 <cstdio> | |
using namespace std; | |
const int max_row = 4; | |
const int max_col = 10; | |
int runtime = 0; | |
char visited = 'V'; | |
char map[max_row][max_col]; | |
int found = 0; | |
void find_path(int i, int j) | |
{ | |
runtime++; | |
if(i < 0 || j < 0 || i >= max_row || j >= max_col) | |
{ | |
cout << "Out of Boundary" << endl; | |
return; // if we go out of area then return; | |
} | |
else if(map[i][j] == 'B') | |
{ | |
cout << "Found B" << endl; | |
found = 1; // menon can reach to final destination; | |
return; | |
} | |
else if(map[i][j] == 'X') | |
{ | |
cout << "Found X" << endl; | |
return; // we can't go through this road; | |
} | |
else if(map[i][j] == 'v') { | |
return; | |
} | |
else | |
{ | |
// This was the peril zone. | |
if(map[i][j] == '.' || map[i][j] == 'M') { | |
map[i][j] = 'v'; // seal the peril position :) | |
} | |
find_path(i - 1, j); // go up | |
find_path(i, j + 1); // go right | |
find_path(i + 1, j); // go down | |
find_path(i, j - 1); // go left | |
} | |
} | |
int main() | |
{ | |
freopen("DFS_recursion.txt", "r+", stdin); | |
int row, col; | |
char value; | |
// cin >> row >> col; | |
// cin.ignore(); | |
row = max_row; col = max_col; | |
for(int i = 0; i < row; i++) | |
{ | |
for(int j = 0; j < col; j++) | |
{ | |
cin >> value; | |
map[i][j] = value; | |
} | |
} | |
int starting_row = 0, starting_col = 0; | |
//cin >> starting_row >> starting_col; | |
// cout << "Done" << endl; | |
for(int i = 0; i < max_row; i++) | |
{ | |
for(int j = 0; j < max_col; j++) | |
{ | |
cout << map[i][j]; | |
} | |
cout << endl; | |
} | |
find_path(starting_row, starting_col); | |
if(found == 1) | |
cout << "We can reach our destination :)" << endl; | |
else | |
cout << "We can't reach our destination :(" << endl; | |
return 0; | |
} |
Comments
Post a Comment