//
// main.cpp
// Rat in the Maze
//
// Created by Himanshu on 25/09/21.
//
#include <iostream>
using namespace std;
const int N = 4;
void printPath(int sol[][N]) {
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
cout<<sol[i][j]<<" ";
}
cout<<endl;
}
}
bool solve (int maze[N][N], int x, int y, int sol[N][N]) {
if (x == N-1 && y == N-1) {
sol[x][y] = 1;
return true;
}
if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) {
sol[x][y] = 1;
if (solve(maze, x+1, y, sol)) {
return true;
}
if (solve(maze, x, y+1, sol)) {
return true;
}
sol[x][y] = 0;
}
return false;
}
int main() {
int maze[N][N] = {{1, 1, 0, 0},
{1, 1, 1, 0},
{0, 1, 0, 1},
{0, 1, 1, 1}};
int sol[N][N];
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
sol[i][j] = 0;
}
}
if (solve(maze, 0, 0, sol)) {
cout<<"Path exists. Path is marked with 1:"<<endl;
printPath(sol);
} else {
cout<<"Path does not exist";
}
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBSYXQgaW4gdGhlIE1hemUKLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMjUvMDkvMjEuCi8vCgojaW5jbHVkZSA8aW9zdHJlYW0+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CmNvbnN0IGludCBOID0gNDsKCnZvaWQgcHJpbnRQYXRoKGludCBzb2xbXVtOXSkgewogICAgZm9yIChpbnQgaT0wOyBpPE47IGkrKykgewogICAgICAgIGZvciAoaW50IGo9MDsgajxOOyBqKyspIHsKICAgICAgICAgICAgY291dDw8c29sW2ldW2pdPDwiICI7CiAgICAgICAgfQogICAgICAgIGNvdXQ8PGVuZGw7CiAgICB9Cn0KCmJvb2wgc29sdmUgKGludCBtYXplW05dW05dLCBpbnQgeCwgaW50IHksIGludCBzb2xbTl1bTl0pIHsKICAgIGlmICh4ID09IE4tMSAmJiB5ID09IE4tMSkgewogICAgICAgIHNvbFt4XVt5XSA9IDE7CiAgICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgICAKICAgIGlmICh4ID49IDAgJiYgeCA8IE4gJiYgeSA+PSAwICYmIHkgPCBOICYmIG1hemVbeF1beV0gPT0gMSkgewogICAgICAgIHNvbFt4XVt5XSA9IDE7CgogICAgICAgIGlmIChzb2x2ZShtYXplLCB4KzEsIHksIHNvbCkpIHsKICAgICAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgICAgfQogICAgICAgIGlmIChzb2x2ZShtYXplLCB4LCB5KzEsIHNvbCkpIHsKICAgICAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgICAgfQoKICAgICAgICBzb2xbeF1beV0gPSAwOwogICAgfQoKICAgIHJldHVybiBmYWxzZTsKfQoKaW50IG1haW4oKSB7CiAgICBpbnQgbWF6ZVtOXVtOXSA9IHt7MSwgMSwgMCwgMH0sCiAgICAgICAgICAgICAgICAgICAgIHsxLCAxLCAxLCAwfSwKICAgICAgICAgICAgICAgICAgICAgezAsIDEsIDAsIDF9LAogICAgICAgICAgICAgICAgICAgICB7MCwgMSwgMSwgMX19OwogICAgCiAgICBpbnQgc29sW05dW05dOwogICAgZm9yIChpbnQgaT0wOyBpPE47IGkrKykgewogICAgICAgIGZvciAoaW50IGo9MDsgajxOOyBqKyspIHsKICAgICAgICAgICAgc29sW2ldW2pdID0gMDsKICAgICAgICB9CiAgICB9CiAgICAKICAgIGlmIChzb2x2ZShtYXplLCAwLCAwLCBzb2wpKSB7CiAgICAgICAgY291dDw8IlBhdGggZXhpc3RzLiBQYXRoIGlzIG1hcmtlZCB3aXRoIDE6Ijw8ZW5kbDsKICAgICAgICBwcmludFBhdGgoc29sKTsKICAgIH0gZWxzZSB7CiAgICAgICAgY291dDw8IlBhdGggZG9lcyBub3QgZXhpc3QiOwogICAgfQoKICAgIHJldHVybiAwOwp9