From 9c398885517a189cb0063dd2994b5cbf33e412cb Mon Sep 17 00:00:00 2001 From: Andinus Date: Wed, 3 Nov 2021 21:20:30 +0530 Subject: java/DFS: Chose neighbor randomly This does mean that we might end up taking a longer path but also the inverse! --- algorithms/java/DFS.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/algorithms/java/DFS.java b/algorithms/java/DFS.java index 8d1e341..e2f866e 100644 --- a/algorithms/java/DFS.java +++ b/algorithms/java/DFS.java @@ -1,3 +1,7 @@ +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + public class DFS { static int[][] directions = new int[][]{ {+0, +1}, // Right. @@ -7,7 +11,11 @@ public class DFS { }; static void traverse(int x, int y, char[][] maze, boolean[][] visited) { - for (int i = 0; i < 4; i++) { + // Move in random direction. + List l = Arrays.asList(new Integer[]{0, 1, 2, 3}); + Collections.shuffle(l); + + for (int i: l) { int curx = x + directions[i][0]; int cury = y + directions[i][1]; -- cgit 1.4.1-2-gfad0