solved s08 ex4

This commit is contained in:
navid.sassan 2020-11-16 17:01:48 +01:00
parent 11cf6cae90
commit c2c2f058d4
2 changed files with 69 additions and 4 deletions

View File

@ -1,6 +1,22 @@
package ch.zhaw.ads;
import java.util.*;
class LabyrinthNode<E> extends Node<E> {
boolean mark;
LabyrinthNode<E> prev;
public class LabyrinthNode<E> extends Node<E> {
public void setMark(boolean m) {
mark = m;
}
public boolean getMark() {
return mark;
}
public void setPrev(LabyrinthNode<E> prev) {
this.prev = prev;
}
public LabyrinthNode<E> getPrev() {
return prev;
}
}

View File

@ -6,7 +6,7 @@ public class LabyrinthServer implements CommandExecutor {
final double SCALE = 10;
private ServerGraphics serverGraphics;
private Graph<LabyrinthNode, Edge> graph;
Graph<LabyrinthNode, Edge> graph;
@Override
public String execute(String command) {
@ -17,19 +17,68 @@ public class LabyrinthServer implements CommandExecutor {
serverGraphics.setColor(Color.BLACK);
serverGraphics.fillRect(0, 0, 1, 1);
// read in data
for (String record : command.split("\\r?\\n")) {
String[] values = record.split(" ");
try {
graph.addEdge(values[0], values[1], 0.0);
graph.addEdge(values[1], values[0], 0.0);
} catch (Throwable e) {}
} catch (Throwable e) {
e.printStackTrace();
}
this.drawPath(serverGraphics, values[0], values[1], false);
}
// find path
// start and goal are taken from the picture in the exercise
LabyrinthNode<Edge> start = graph.findNode("0-6");
LabyrinthNode<Edge> goal = graph.findNode("3-0");
this.unmarkAll();
if (this.search(start, goal)) {
LabyrinthNode<Edge> current = goal;
while (current.getPrev() != null) {
LabyrinthNode<Edge> prev = current.getPrev();
this.drawPath(serverGraphics, current.getName(), prev.getName(), true);
current = prev;
}
} else {
System.out.println("Failed to find path.");
}
return serverGraphics.getTrace();
}
private void unmarkAll() {
for (LabyrinthNode<Edge> node : graph.getNodes()) {
node.setMark(false);
node.setPrev(null);
}
}
private boolean search(LabyrinthNode<Edge> currentNode, LabyrinthNode<Edge> goal) {
currentNode.setMark(true);
if (currentNode.equals(goal)) return true;
for (Edge<LabyrinthNode> edge : currentNode.getEdges()) {
LabyrinthNode<Edge> sucessor = edge.getDest();
if (!sucessor.getMark()) {
if (this.search(sucessor, goal)) {
sucessor.setPrev(currentNode);
return true;
}
}
}
currentNode.setMark(false);
return false;
}
private void drawPath(ServerGraphics g, String from, String to, boolean mouse) {
if (mouse) serverGraphics.setColor(Color.RED);
else serverGraphics.setColor(Color.WHITE);