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 616f424

Browse files
algorithms/src/main/java/ivanmarkovic/algorithms/recursion/Maze.java
1 parent 23848ed commit 616f424

File tree

1 file changed

+79
-0
lines changed
  • algorithms/src/main/java/ivanmarkovic/algorithms/recursion

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package ivanmarkovic.algorithms.recursion;
2+
3+
import java.util.Stack;
4+
5+
public class Maze {
6+
7+
public static void main(String args[]) {
8+
Stack<int []> stack = new Stack<>();
9+
int numbers[] = {0, 0};
10+
stack.push(numbers);
11+
12+
int matrix[][] = new int[5][5];
13+
for(int i = 0; i < matrix.length; i++)
14+
for(int j = 0; j < matrix[i].length; j++)
15+
matrix[i][j] = 0;
16+
17+
18+
matrix[0][0] = 1; // Must be 1, it's starting position
19+
for(int i = 2; i < matrix[0].length; i++)
20+
matrix[0][i] = 2;
21+
matrix[1][0] = 2;
22+
for(int i = 0; i < matrix[2].length; i++)
23+
if(i != 2)
24+
matrix[2][i] = 2;
25+
for(int i = 0; i < matrix[4].length; i++)
26+
if(i != 4)
27+
matrix[4][i] = 2;
28+
29+
30+
move(matrix, stack);
31+
}
32+
33+
public static void move(int matrix[][], Stack<int[]> stack) {
34+
if(stack.isEmpty())
35+
System.out.println("Path not found");
36+
else {
37+
int newCoords[] = new int[2];
38+
int coords[] = new int[2];
39+
coords = stack.peek();
40+
Integer x = coords[0];
41+
Integer y = coords[1];
42+
if(x == matrix.length - 1 && y == matrix[x].length - 1) {
43+
System.out.println("Path found");
44+
}
45+
else if(y < matrix[x].length - 1 && matrix[x][y + 1] == 0) { // can go right
46+
matrix[x][y + 1] = 1;
47+
newCoords[0] = x;
48+
newCoords[1] = y + 1;
49+
stack.push(newCoords);
50+
move(matrix, stack);
51+
}
52+
else if(x - 1 >= 0 && matrix[x - 1][y] == 0) { // can go up
53+
matrix[x - 1][y] = 1;
54+
newCoords[0] = x - 1;
55+
newCoords[1] = y;
56+
stack.push(newCoords);
57+
move(matrix, stack);
58+
}
59+
else if(y - 1 >= 0 && matrix[x][y - 1] == 0) { // can go left
60+
matrix[x][y - 1] = 1;
61+
newCoords[0] = x;
62+
newCoords[1] = y - 1;
63+
stack.push(newCoords);
64+
move(matrix, stack);
65+
}
66+
else if(x < matrix.length - 1 && matrix[x + 1][y] == 0) { // can go down
67+
matrix[x + 1][y] = 0;
68+
newCoords[0] = x + 1;
69+
newCoords[1] = y;
70+
stack.push(newCoords);
71+
move(matrix, stack);
72+
}
73+
else {
74+
stack.pop();
75+
move(matrix, stack);
76+
}
77+
}
78+
}
79+
}

0 commit comments

Comments
(0)

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