Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cef5e24

Browse files
Create README.md
A detailed description of the problem
1 parent ae4029c commit cef5e24

File tree

1 file changed

+45
-0
lines changed
  • Practice Problems/Backtracking/Rat In A Maze

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Rat In A Maze
2+
3+
**Problem from GeeksForGeeks**
4+
A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move only in two directions: forward and down.
5+
In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves.
6+
7+
Algorithm:
8+
If destination is reached
9+
print the solution matrix
10+
Else
11+
a) Mark current cell in solution matrix as 1.
12+
b) Move forward in the horizontal direction and recursively check if this
13+
move leads to a solution.
14+
c) If the move chosen in the above step doesn't lead to a solution
15+
then move down and check if this move leads to a solution.
16+
d) If none of the above solutions works then unmark this cell as 0
17+
(BACKTRACK) and return false.
18+
19+
20+
### Example:
21+
22+
**Input** :
23+
```java
24+
maze[][] = { { 1, 0, 0, 0 },
25+
{ 1, 1, 0, 1 },
26+
{ 0, 1, 0, 0 },
27+
{ 1, 1, 1, 1 } }
28+
```
29+
30+
**Output:** :
31+
```java
32+
The 1 values show the path of rat.
33+
1 0 0 0
34+
1 1 0 0
35+
0 1 0 0
36+
0 1 1 1
37+
```
38+
39+
40+
Complexity Analysis:
41+
42+
Time Complexity: O(2^(n^2)).
43+
The recursion can run upperbound 2^(n^2) times.
44+
Space Complexity: O(n^2).
45+
Output matrix is required so an extra space of size n*n is needed.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /