Skip to content

Commit 65f84fb

Browse files
dhananjay-ngDhananjay Nagargoje
authored and
Dhananjay Nagargoje
committed
more backtracking
1 parent b0c03e6 commit 65f84fb

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package problems.onRecursionAndDp.backtracking;
2+
3+
import java.util.ArrayList;
4+
5+
public class Suduko {
6+
public class Solution {
7+
public void solveSudoku(ArrayList<ArrayList<Character>> a) {
8+
for(int i=0;i<9;i++) {
9+
for(int j=0;j<9;j++){
10+
solve(a, i,j);
11+
}
12+
}
13+
}
14+
15+
public boolean solve(ArrayList<ArrayList<Character>> a, int row, int col) {
16+
if(col >= 9){ col=0;row++;}
17+
if(row >= 9) return true;
18+
if(Character.isDigit(a.get(row).get(col))) {
19+
return solve(a, row, col+1);
20+
}
21+
22+
for(int i=1;i<=9;i++) {
23+
if(isValid(a, row, col, (char)('0'+i))){
24+
a.get(row).set(col, (char)('0'+i));
25+
if(solve(a, row, col+1)) return true;
26+
}
27+
}
28+
a.get(row).set(col, '.');
29+
return false;
30+
}
31+
32+
boolean isValid(ArrayList<ArrayList<Character>> a, int row, int col, Character x) {
33+
int rowst = (row/3)*3;
34+
int colst = (col/3)*3;
35+
for(int i=rowst;i<rowst+3;i++){
36+
for(int j=colst;j<colst+3;j++) {
37+
if(a.get(i).get(j).equals(x)) return false;
38+
}
39+
}
40+
41+
for(int j=0;j<9;j++){
42+
if(a.get(row).get(j).equals(x)) return false;
43+
}
44+
for(int i=0;i<9;i++){
45+
if(a.get(i).get(col).equals(x)) return false;
46+
}
47+
return true;
48+
}
49+
}
50+
51+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package problems.onRecursionAndDp.backtracking;
2+
3+
public class VisiteAllMazePaths {
4+
public class Solution {
5+
int count;
6+
public int solve(int[][] A) {
7+
this.count = 0;
8+
for(int i=0;i<A.length;i++){
9+
for(int j=0;j<A[0].length;j++){
10+
if(A[i][j]==1) {
11+
solve(A, i, j, 0);
12+
return this.count;
13+
}
14+
}
15+
}
16+
return this.count;
17+
}
18+
19+
public boolean solve(int [][] A, int x, int y, int visited) {
20+
if(x<0 || x>=A.length || y<0 || y> A[0].length || A[x][y] == -1 || A[x][y] == -2) return false;
21+
visited++;
22+
if(A[x][y] == 2) {
23+
if(visited == A.length*A[0].length) {
24+
this.count++;
25+
}
26+
visited++;
27+
return false;
28+
}
29+
A[x][y] = -2;
30+
solve(A,x+1,y, visited);
31+
solve(A,x-1,y, visited);
32+
solve(A,x,y+1, visited);
33+
solve(A,x,y-1, visited);
34+
35+
visited--;
36+
return false;
37+
}
38+
}
39+
40+
}

0 commit comments

Comments
 (0)