-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathbacktraking.java
83 lines (64 loc) · 1.79 KB
/
backtraking.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.Scanner;
public class backtraking {
static int[][] oArr;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter N:\t");
int N = sc.nextInt();
int[][] inArr = new int[N][N];
oArr = new int[N][N];
//Input arr '0' for block and '1' for pass
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
inArr[i][j] = sc.nextInt();
oArr[i][j] = 0;
}
}
//start the game
ratInMaze(inArr, 0, 0, N);
//print the path (final output)
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
System.out.print(oArr[i][j]+"\t");
}
System.out.print("\n");
}
}
public static boolean ratInMaze(int[][] inArr, int x, int y, int n)
{
if(x==(n-1) && y==(n-1))
{
oArr[x][y]=1;
return true;
}
if(isSafe(inArr, x, y, n))
{
oArr[x][y] = 1;
if(ratInMaze(inArr, x+1, y, n))
{
return true;
}
if(ratInMaze(inArr, x, y+1, n))
{
return true;
}
//backtracking
oArr[x][y]=0;
return false;
}
return false;
}
//Check whether rat can pass thorugh given block or not
public static boolean isSafe(int[][] inArr, int x, int y, int n)
{
if(x<n && y<n && inArr[x][y]==1)
{
return true;
}
return false;
}
}