I am implementing a DFS to find the exit of a maze, and currently it is single threaded.
I am planning on making it more efficient by creating several threads that search the tree using the same single-threaded algorithm, but I am randomizing which direction to go in when I encounter an intersection.
For example, the threads encounter an intersection where they can go East or West. Half of them go East and half go West. This continues until one of the threads finds the solution path.
Is this a valid way to implement DFS in a parallel way?
If you do recursive parallel work in Java, use the Fork and Join API introduced in Java 7.
public class MazeNode {
// This class represents a Path from the start of your maze to a certain node. It can be a) a dead end, b) the exit, c) have child Paths
...
}
public class MazeTask extends RecursiveTask<MazeNode>
{
private MazeNode node;
MazeTask(MazeNode node) {
this.node = node;
}
// Returns null or the exit node
@Override
protected MazeNode compute() {
if (node.isDeadEnd())
return null;
else if (node.isExit())
return node;
else { // node has ways to go
// implement as many directions as you want
MazeTask left = new MazeTask(node.getLeft());
MazeTask right = new MazeTask(node.getRight());
left.fork(); // calculate in parallel
MazeNode rightNode = right.compute(); // calculate last Task directly to save threads
MazeNode leftNode = left.join(); // Wait for the other task to complete and get result
if (rightNode != null)
return rightNode;
else
return leftNode; // This assumes there is only one path to exit
}
}
public static void main(String[] args) {
MazeNode maze = ...
MazeNode exit = new ForkJoinPool().invoke(new MazeTask(maze));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With