BACKTRACKING Solutions
BACKTRACKING Solutions
BACKTRACKING Solutions
poojadhiman69424@gmail.com
Solution 1:
Algorithm -
1. Create a solution matrix, initially filled with 0’s.
2. Create a recursive function, which takes the initial matrix, output matrix and position
of rat (i, j).
3. if the position is out of the matrix or the position is not valid then return.
4. Mark the position output[i][j] as 1 and check if the current position is destination or
not. If destination is reached print the output matrix and return.
5. Recursively call for position (i+1, j) and (i, j+1).
6. Unmark position (i, j), i.e output[i][j] = 0.
poojadhiman69424@gmail.com
if (x == maze.length - 1 && y == maze.length - 1 && maze[x][y] == 1) {
sol[x][y] = 1;
return true;
}
return false;
}
solveMaze(maze);
}
}
Solution 2:
poojadhiman69424@gmail.com
public class Solution {
final static 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'}};
public static void bfs(int pos, int len, StringBuilder sb, String D) {
if (pos == len){
System.out.println(sb.toString());
}
else {
char[] letters = L[Character.getNumericValue(D.charAt(pos))];
for (int i = 0; i < letters.length; i++)
bfs(pos+1, len, new StringBuilder(sb).append(letters[i]), D);
}
}
public static void main(String args[]){
letterCombinations("2");
}
}
Solution 3 :
poojadhiman69424@gmail.com
public static void printSolution(int sol[][]) {
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++)
System.out.print(sol[x][y] + " ");
System.out.println();
}
}
return true;
}
poojadhiman69424@gmail.com
if (isSafe(next_x, next_y, sol)) {
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1,
sol, xMove, yMove))
return true;
else
sol[next_x][next_y]
= -1; // backtracking
}
}
return false;
}