import
java.util.*;
public
class
GFG {
static
class
direction {
int
x, y;
char
c;
direction(
int
x,
int
y,
char
c)
{
this
.c = c;
this
.x = x;
this
.y = y;
}
};
static
boolean
isCorner(
int
i,
int
j,
int
M,
int
N)
{
if
((i ==
0
&& j ==
0
) || (i ==
0
&& j == N -
1
)
|| (i == M -
1
&& j == N -
1
)
|| (i == M -
1
&& j ==
0
))
return
true
;
return
false
;
}
static
boolean
isValid(
int
i,
int
j,
int
M,
int
N)
{
if
(i <
0
|| i >= M || j <
0
|| j >= N)
return
false
;
return
true
;
}
static
void
solve(
int
i,
int
j,
int
M,
int
N,
direction dir[],
int
[][] maze,
String t, ArrayList<String> ans)
{
if
(isCorner(i, j, M, N)) {
ans.add(t);
return
;
}
for
(
int
k =
0
; k <
4
; k++) {
int
x = i + dir[k].x;
int
y = j + dir[k].y;
char
c = dir[k].c;
if
(isValid(x, y, M, N) && maze[x][y] ==
1
) {
maze[x][y] =
0
;
t += c;
solve(x, y, M, N, dir, maze, t, ans);
t = t.substring(
0
, t.length() -
1
);
maze[x][y] =
1
;
}
}
return
;
}
static
ArrayList<String> possiblePaths(
int
[] src,
int
[][] maze)
{
direction[] dir = {
new
direction(-
1
,
0
,
'U'
),
new
direction(
0
,
1
,
'R'
),
new
direction(
1
,
0
,
'D'
),
new
direction(
0
, -
1
,
'L'
) };
String temp =
""
;
ArrayList<String> ans =
new
ArrayList<>();
solve(src[
0
], src[
1
], maze.length, maze[
0
].length,
dir, maze, temp, ans);
return
ans;
}
public
static
void
main(String[] args)
{
int
[][] maze = {
{
1
,
0
,
0
,
1
,
0
,
0
,
1
,
1
},
{
1
,
1
,
1
,
0
,
0
,
0
,
1
,
0
},
{
1
,
0
,
1
,
1
,
1
,
1
,
1
,
0
},
{
0
,
0
,
0
,
0
,
1
,
0
,
0
,
0
},
{
1
,
0
,
1
,
0
,
1
,
0
,
0
,
1
},
{
0
,
1
,
1
,
1
,
1
,
0
,
0
,
1
},
{
0
,
1
,
0
,
0
,
1
,
1
,
1
,
1
},
{
1
,
1
,
0
,
0
,
0
,
0
,
0
,
1
},
};
int
[] src = {
4
,
2
};
ArrayList<String> paths = possiblePaths(src, maze);
if
(paths.size() ==
0
) {
System.out.println(
"No Possible Paths"
);
return
;
}
for
(
int
i =
0
; i < paths.size(); i++) {
System.out.println(paths.get(i));
}
}
}