package progs.graphs;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import progs.lib.BFS;
import progs.lib.Graph;
import java.util.List;
import java.util.Set;
import static progs.lib.Graph.Node;
/**
* For a given grid with walls (marked as #) and equipment (marked as x), find an empty square
* that has the minimum distance to all the four squares.
* Solution is marked as t.
*
* @author KRishna Atkuru
*/
@RunWith(JUnit4.class)
public class OptimizedDistanceFromKStations {
@Test
public void test() {
Solution solution = new Solution();
String[] room = new String[]{
"############",
"# *# #",
"# # #",
"# t #",
"# ## #",
"# *# ## #",
"# # # *#",
"############"};
Assert.assertEquals(new Node(3, 5), solution.solveFor(room));
room = new String[]{
"+++",
"+++",
"*t*"};
Assert.assertEquals(new Node(2, 1), solution.solveFor(room));
room = new String[]{
"+++",
"+t+",
"*#*"};
solution = new Solution();
Assert.assertEquals(new Node(1, 1), solution.solveFor(room));
}
static class Solution {
public Node solveFor(String[] room) {
Graph graph = Graph.fromStringArray(room);
List<Node> specialNodes = graph.getSpecialNodes();
Set<Node> nodes = graph.getAllNodes();
BFS bfs = new BFS(graph);
int previousMinDistance = Integer.MAX_VALUE;
Node bestNodeSoFar = null;
for (Node node : nodes) {
if (specialNodes.contains(node)) {
continue;
}
int localDistance = 0;
for (Node stationNode : specialNodes) {
localDistance += bfs.distanceFrom(stationNode, node);
}
if (localDistance < previousMinDistance) {
previousMinDistance = localDistance;
bestNodeSoFar = node;
}
}
System.out.println("The best distance is " + previousMinDistance);
return bestNodeSoFar;
}
}
}