Backtracking Solutions
Backtracking Solutions
(Assignment Solutions)
Solution 1:
Hint : To track which cell has or not been visited, create a NxN vector called visited.
This vector will be initialized with false values for all cells & make the value for a particular cell
to true when you have visited it.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//up
if(x-1 >= 0 && !vis[x-1][y] && maze[x-1][y] == 1) {
vis[x][y] = true;
solveMazeUtil(maze, x-1, y, sol+"U", N, vis);
vis[x][y] = false;
}
//down
if(x+1 < N && !vis[x+1][y] && maze[x+1][y] == 1) {
vis[x][y] = true;
solveMazeUtil(maze, x+1, y, sol+"D", N, vis);
vis[x][y] = false;
//right
if(y+1 < N && !vis[x][y+1] && maze[x][y+1] == 1) {
vis[x][y] = true;
solveMazeUtil(maze, x, y+1, sol+"R", N, vis);
vis[x][y] = false;
}
//left
if(y-1 >= 0 && !vis[x][y-1] && maze[x][y-1] == 1) {
vis[x][y] = true;
solveMazeUtil(maze, x, y-1, sol+"L", N, vis);
vis[x][y] = false;
}
}
}
int main(){
int n = 4;
int maze[4][4] = { { 1, 0, 0, 0 },
{ 1, 1, 0, 1 },
{ 1, 1, 0, 0 },
{ 0, 1, 1, 1 } };
solveMaze(maze, n);
}
Solution 2:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void bfs(int pos, int len, string ans, string Dig, vector<vector<char>> L) {
if (pos == len){
cout << ans << endl;
} else {
vector<char> letters = L[Dig[pos]-'0'];
for (int i = 0; i < letters.size(); i++)
int main(){
vector<vector<char>> L = {{},{},{'a','b','c'},{'d','e','f'},{'g','h','i'},
{'j','k','l'},{'m','n','o'},{'p','q','r','s'},
{'t','u','v'},{'w','x','y','z'}};
Solution 3 :
#include <iostream>
#include <string>
#include <vector>
using namespace std;
return true;
sol[next_x][next_y]
= -1; // backtracking
}
}
return false;
}
bool solveKT(int N) {
int sol[8][8];
return true;
}
int main(){
int N = 8;
solveKT(N);
}
https://t.me/+nEKeBr_yhXtmY2Yx
https://telegram.me/+nEKeBr_yhXtmY2Yx
One and only Team Groww Study aka TGS