Connected components in a DAG - java

I currently have a program that takes a DAG represented by an adjacency list as a system input, converts it into a adjacency matrix and then runs a DFS on the adjacency matrix which outputs the number of connected components.
e.g. the first line represents the total number of nodes with the following lines representing each edge for that node. The following graph..
corresponds to the following input..
where the output 3 is the number of connected components.
My issue is that the following code does not work for all graphs, sometimes outputting a larger number of components than should be expected. Any clues to why this is happening would be very useful.
public class conComponents {
private Stack<Integer> stack = new Stack<Integer>();
public static void main(String[] args) {
int numNodes;
Scanner sc = null;
try {
sc = new Scanner(System.in);
while (sc.hasNext()) {
numNodes = sc.nextInt();
if (numNodes == 0)
break;
sc.nextLine();
int adjMatrix[][] = new int[numNodes][numNodes];
for (int s = 0; s < numNodes; s++) {
String[] split = sc.nextLine().split(" ");
for (int i = 0; i < numNodes; i++) {
if (i < split.length) {
if (adjMatrix[s][i] != 1) {
adjMatrix[s][i] = 0;
}
if (split[i].equals("")) {
adjMatrix[s][i] = 0;
} else {
adjMatrix[s][Integer.valueOf(split[i])] = 1;
}
}
}
}
for (int i = 0; i < numNodes; i++) {
for (int j = 0; j < numNodes; j++) {
if (adjMatrix[i][j] == 1 && adjMatrix[j][i] == 0) {
adjMatrix[j][i] = 1;
}
}
}
conComponents undirectedConnectivity = new conComponents();
undirectedConnectivity.dfs(adjMatrix);
}
} catch (InputMismatchException inputMismatch) {
System.out.println("Wrong Input format");
}
sc.close();
}
public void dfs(int adjMatrix[][]) {
int numNodes = adjMatrix[0].length;
int visited[] = new int[numNodes];
int cc = 0;
for (int vertex = 0; vertex < numNodes; vertex++) {
if (visited[vertex] == 0) {
int element = vertex;
int i = vertex;
visited[vertex] = 1;
cc++;
stack.push(vertex);
while (!stack.isEmpty()) {
element = stack.peek();
i = element;
while (i < numNodes) {
if (adjMatrix[element][i] == 1 && visited[i] == 0) {
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
continue;
}
i++;
}
stack.pop();
}
}
}
System.out.println(cc);
}
}

Related

How to get sum of array elements between two zeros

first input: size of array: 5
second input: 0 -2 4 0 6
output: 2
Here is what I have tried. It is also adding the numbers before zero:
My code's output:
array size: 10
elements: 6 19 0 -3 4 8 0 -6 9 59
my output: 25 9
import java.util.Scanner;
import java.util.Vector;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
Vector<Integer> A = new Vector<Integer>();
int sum = 0;
for(int i=0; i<arr.length; i++){
arr[i] = in.nextInt();
}
for(int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
i++;
break;
}
}
for(int i=0; i < arr.length; i++)
{
if (arr[i] == 0)
{
A.add(sum);
sum = 0;
}
else
{
sum += arr[i];
}
}
for(int j = 0; j < A.size(); j++)
{
System.out.print(A.get(j) + " ");
}
}
}
You don't need 2 loops, one to look for the first zero and then sum up.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
List<Integer> sums = new ArrayList<>();
int sum = 0;
// read input
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
boolean isCounting = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0 && isCounting) {
sum += arr[i];
} else if(arr[i] == 0){
// if already counting then finish the sum
if (isCounting) {
sums.add(sum);
sum = 0;
} else { // else start counting
isCounting = true;
}
}
}
System.out.println(sums);
}
}
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int arr[] = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
int sum = 0;
int idx = 0;
while (arr[idx] != 0)
idx++; // After this, idx will be the index of the first 0
do {
idx++; // Keep looping from idx + 1 until the next 0
if (arr[idx] != 0 && idx < arr.length)
sum += arr[idx];
} while (idx < arr.length && arr[idx] != 0);
System.out.println("Sum = " + sum);
}
}
int sum = -1;
int j = -1;
for(int i=0; i<arr.length;i++ ){
if (arr[i] == 0) {
j = i;
if (sum == -1)
sum = 0;
else
break;
}
if ( j == -1)
continue;
sum += arr[i];
}
The above should work
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
int sum = 0;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
if (arr[i] == 0) {
list.add(i);
}
}
for (int i = list.get(0); i <= list.get(list.size()-1); i++) {
sum += arr[i];
}
System.out.println(sum);
}

Finding minimum weight and number of edges traversed in a graph

I have to find the minimum distance between two vertices and no. of edges traversed in finding that minimum distance in a adirected weighted graph. I did write a code on using Dijkstras algo. But my test cases are failing. What am i missing here.?
Ideal input: given any two vertices A,B
Output: min distance between two nodes, no. of edges traversed
If the node is unreachable then output should be -1, -1.
//This is a java program to find the shortest path between source vertex and destination vertex
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Dijkstras_Shortest_Path
{
private int distances[];
private int Numnodes[];
private int numnodes;
private Set<Integer> settled;
private Set<Integer> unsettled;
private int number_of_nodes;
private int adjacencyMatrix[][];
public Dijkstras_Shortest_Path(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
Numnodes=new int[number_of_nodes+1];
settled = new HashSet<Integer>();
unsettled = new HashSet<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{
distances[i] = Integer.MAX_VALUE;
}
unsettled.add(source);
distances[source] = 0;
while (!unsettled.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode);
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getNodeWithMinimumDistanceFromUnsettled()
{
int min;
int node = 0;
Iterator<Integer> iterator = unsettled.iterator();
node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (unsettled.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}
}
}
return node;
}
private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
int newNodes=1;
for (int destinationNode = 1; destinationNode <= number_of_nodes;
destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] !=
Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode]
[destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
newNodes=Numnodes[evaluationNode]+1;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
Numnodes[destinationNode]=newNodes;
}
unsettled.add(destinationNode);
}
}
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int number_of_edges;
int source = 0, destination = 0;
Scanner scan = new Scanner(System.in);
try
{
number_of_vertices = scan.nextInt();
number_of_edges=scan.nextInt();
if (number_of_vertices<1||number_of_vertices>10000)
{
System.out.println("Number of vertices out of boundary");
}
if (number_of_edges<1||number_of_edges>10000)
{
System.out.println("Number of edges out of boundary");
}
adjacency_matrix = new int[number_of_vertices + 1]
[number_of_vertices + 1];
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = 0;
}
}
for(int i=1;i<=number_of_edges;i++)
{
int node1=scan.nextInt();
int node2=scan.nextInt();
adjacency_matrix[node1][node2]=scan.nextInt();
}
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
source = scan.nextInt();
destination = scan.nextInt();
Dijkstras_Shortest_Path dijkstrasAlgorithm = new
Dijkstras_Shortest_Path(
number_of_vertices);
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix, source);
for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1; i++)
{
if (i == destination)
System.out.println(dijkstrasAlgorithm.distances[i] +" "+
dijkstrasAlgorithm.Numnodes[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}

How do I get rid of these errors in my code? NumberFormatException: for input string: ""

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at HelloWorld.main(HelloWorld.java:169)
These errors continue to pop up when I run my code against our sample input. We are given a document with polygons and have to use kruskal's algorithm and build a minimal spanning tree to find the shortest distance to each island without creating a cycle. If anyone can help or give advice on how to get rid of these errors that would be great! I dont understand how there can be a numberformatexception on a string ""....
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
public class HelloWorld {
static class Point {
int x = 0;
int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "(x: " + x + " y: " + y + ")";
}
}
static class Polygon {
int numberOfVertices = 0;
ArrayList<Point> points = new ArrayList<Point>();
public Polygon(int numberOfVertices, ArrayList<Point> points) {
this.numberOfVertices = numberOfVertices;
this.points = points;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < points.size(); i++) {
Point point = this.points.get(i);
stringBuilder.append(point);
}
return stringBuilder.toString();
}
}
static class PQItem implements Comparable<PQItem> {
int node1;
int node2;
double edge;
public PQItem(int node1, int node2, double edge) {
this.node1 = node1;
this.node2 = node2;
this.edge = edge;
}
public int compareTo(PQItem T) {
if (edge - T.edge < 0)
return 1;
else if (edge - T.edge > 0)
return -1;
else
return 0;
}
}
public static void BuildMinimalSpanningTree(int numberOfIslands, ArrayList<Polygon> polygons) {
PriorityQueue q = new PriorityQueue((numberOfIslands * numberOfIslands) / 2);
PQItem Temp;
int[] CheckPad = new int[numberOfIslands];
int FootPrint = 0;
int counter = 0;
double length = 0;
for (int i = 0; i < polygons.size(); i++)
for (int j = 0; j < polygons.size(); j++) {
Temp = new PQItem(i, j, ShortestDistance(polygons.get(i), polygons.get(j)));
}
for (int i = 0; i < polygons.size(); i++)
CheckPad[i] = -1 - i;
while (counter < polygons.size() - 1) {
Temp = (PQItem) q.Remove();
for (int i = 0; i < polygons.size(); i++)
for (int j = 0; j < polygons.size(); j++)
if (CheckPad[Temp.node1] != CheckPad[Temp.node2]) {
if (CheckPad[Temp.node1] < 0 && CheckPad[Temp.node2] < 0) {
CheckPad[Temp.node1] = FootPrint;
CheckPad[Temp.node2] = FootPrint;
FootPrint = FootPrint + 1;
}
else if (CheckPad[Temp.node1] < 0) {
CheckPad[Temp.node1] = CheckPad[Temp.node2];
}
else if (CheckPad[Temp.node2] < 0) {
CheckPad[Temp.node2] = CheckPad[Temp.node1];
}
else {
if (CheckPad[Temp.node1] < CheckPad[Temp.node2]) {
for (i = 0; i < polygons.size(); i++) {
if (CheckPad[i] == CheckPad[Temp.node2])
CheckPad[i] = CheckPad[Temp.node2];
else
for (j = 0; j < polygons.size(); j++)
if (CheckPad[j] == CheckPad[Temp.node2])
CheckPad[j] = CheckPad[Temp.node2];
}
}
System.out.println(Temp.edge);
length += Temp.edge;
counter++;
}
}
}
}
static double ShortestDistance(Polygon polygon1, Polygon polygon2) {
double shortestdistance = 0;
double Temporary = 0;
for (int i = 0; i < polygon1.numberOfVertices; i++)
for (int j = 0; j < polygon2.numberOfVertices; j++) {
Temporary = Math.pow(polygon1.points.get(i).x - polygon2.points.get(j).x, 2)
+ Math.pow(polygon1.points.get(i).y - polygon2.points.get(j).y, 2);
if (Temporary < shortestdistance)
shortestdistance = Temporary;
}
return Math.sqrt(shortestdistance);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the name of the file");
File file = new File(scanner.nextLine());
try {
Scanner fileScanner = new Scanner(file);
int numberOfIslands = Integer.parseInt(fileScanner.nextLine());
ArrayList<Polygon> polygons = new ArrayList<Polygon>();
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
String[] numbers = line.split(" ");
ArrayList<Point> points = new ArrayList<Point>();
// PQItem NewItem = new PQItem(Node1, Node2, edge);
// info.Insert(NewItem);
for (int i = 1; i < numbers.length; i += 2) {
Point point = new Point(Integer.parseInt(numbers[i]), Integer.parseInt(numbers[(i + 1)]));
points.add(point);
}
// build tree
Polygon polygon = new Polygon(points.size(), points);
polygons.add(polygon);
// BuildMinSpanTree(numberOfIslands, polygons);
}
for (int i = 0; i < polygons.size(); i++) {
Polygon polygon = polygons.get(i);
System.out.println(polygon);
}
int minimalInterconnect = 0;
int totalLength = 0;
System.out.printf("The minimal interconnect consists of %d bridges with a total length of %d",
minimalInterconnect, totalLength);
} catch (IOException e) {
System.out.println(e);
}
}
HERE IS THE SAMPLE PROGRAM
3
4 0 0 0 1 1 1 1 0
4 2 0 2 1 3 1 3 0
3 4 0 5 0 5 1
public class PriorityQueue {
private Comparable[] HeapArray;
int Last, Limit;
PriorityQueue
public PriorityQueue(int Capacity) {
HeapArray = new Comparable[Capacity + 1];
Last = 0;
Limit = Capacity;
return;
}
// end constructor
public PriorityQueue() {
HeapArray = new Comparable[101];
Last = 0;
Limit = 100;
return;
}
// end constructor
public void Insert(Comparable PQI) {
if (Last == Limit) {
System.out.println("Priority Queue Overflow!");
System.exit(0);
}
// end if
HeapArray[++Last] = PQI;
this.UpHeap(Last);
return;
}
// end public method Insert
private void UpHeap(int k) {
Comparable V;
V = HeapArray[k];
while (k > 1 && HeapArray[k / 2].compareTo(V) < 0) {
HeapArray[k] = HeapArray[k / 2];
k = k / 2;
}
// end while
HeapArray[k] = V;
return;
}
// end private method UpHeap
public Comparable Remove() {
Comparable PQI;
if (Last == 0) {
System.out.println("Priority Queue Underflow!");
System.exit(0);
}
// end if
PQI = HeapArray[1];
HeapArray[1] = HeapArray[Last--];
this.DownHeap(1);
return PQI;
}
// end public method Remove
private void DownHeap(int k) {
Comparable V;
int j;
V = HeapArray[k];
while (k <= Last / 2) {
j = k + k;
if (j < Last && HeapArray[j].compareTo(HeapArray[j + 1]) < 0)
j++;
// end if
if (V.compareTo(HeapArray[j]) >= 0)
break;
// end if
HeapArray[k] = HeapArray[j];
k = j;
}
// end while
HeapArray[k] = V;
return;
}
// end private method DownHeap
public boolean IsEmpty() {
if (Last == 0)
return true;
else
return false;
// end if
}
// end public method IsEmpty
public boolean IsFull() {
if (Last == Limit)
return true;
else
return false;
// end if
}
// end public method IsFull
public int Length() {
return Last;
}
// end public method Length
}
// end class PriorityQueue
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
This is self explanatory. The input is expected as number however the input entered is String ""
The line that reads input and expects the value to be interger :
int numberOfIslands = Integer.parseInt(fileScanner.nextLine());
Provide correct input.
Also you could change the .nextLine() to nextInt()

How to print the path traversed in this Dijkstra's algo?

I am not able to print the path traversed using Dijkstra's algorithm. I am getting the right shortest path cost but not able to print the path or nodes that are being traversed for the shortest path.
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class DijkstraAlgorithmSet
{
private int distances[];
private Set<Integer> settled;
private Set<Integer> unsettled;
private int number_of_nodes;
private int adjacencyMatrix[][];
public DijkstraAlgorithmSet(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>();
unsettled = new HashSet<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{
distances[i] = Integer.MAX_VALUE;
}
unsettled.add(source);
distances[source] = 0;
while (!unsettled.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode);
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getNodeWithMinimumDistanceFromUnsettled()
{
int min ;
int node = 0;
Iterator<Integer> iterator = unsettled.iterator();
node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (unsettled.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}
}
}
return node;
}
private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode] [destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
unsettled.add(destinationNode);
}
}
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Enter the source ");
source = scan.nextInt();
DijkstraAlgorithmSet dijkstrasAlgorithm = new DijkstraAlgorithmSet(number_of_vertices);
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix, source);
System.out.println("The Shorted Path to all nodes are ");
for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1; i++)
{
System.out.println(source + " to " + i + " is "+ dijkstrasAlgorithm.distances[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
As I understand Djikstra's Algorithm for every node you store the current minimum distance needed to get to that node. What you will want to do is to store the path that corresponds to that distance as well. This is slightly tricky considering you are using an adjacency matrix. What you could do is have a second matrix of the same size with the paths stored, I'll call it call it pathMatrix. So if we know that it takes 5 distance units to get from A (i=0, j=0) to C (i=2, j=2) you would have adjacencyMatrix[2][2] = 5 and pathMatrix[2][2] = [A, B, C]. pathMatrix will be updated at the exact same times that adjacencyMatrix is updated. You will just add the next node to the previous node's current path and set it to the next node's entry in pathMatrix.

What shortest path maze algorithm is this?

I am trying to know and understand as many algorithms as I can and I stumbled across a strange algorithm in a contest packet that finds the minimum number of steps to solve a maze (shortest path). I understand it 100%, but I don't know what algorithm it is and the packet did not state the name of it. I would really like to know the name of this algorithm (if it has a name) so I can do more research on it.
import java.io.File;
import java.util.Scanner;
class spot {
char type;
int distance;
spot closest;
public spot() {
type = '.';
distance = Integer.MAX_VALUE;
closest = null;
}
}
public class myalg {
public static void main(String args[]) throws Exception {
int moves = 0;
Scanner keyb = new Scanner(new File("src/mar2014/maze2.txt"));
int rows = keyb.nextInt();
int cols = keyb.nextInt();
spot mat[][] = new spot[rows][cols];
keyb.nextLine();
spot startSpot = null;
spot endSpot = null;
for (int i = 0; i < mat.length; i++) {
String line = keyb.nextLine();
for (int j = 0; j < mat[i].length; j++) {
mat[i][j] = new spot();
mat[i][j].type = line.charAt(j);
if (mat[i][j].type == 'S') {
startSpot = mat[i][j];
startSpot.distance = 0;
startSpot.type = ' ';
}
if (mat[i][j].type == 'E') {
endSpot = mat[i][j];
endSpot.type = ' ';
}
}
}
boolean changeMade = true;
while (changeMade) {
changeMade = false;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
spot thisSpot = mat[i][j];
spot adjacentSpots[] = {null, null, null, null};
if (i > 0) {
adjacentSpots[0] = mat[i - 1][j];
}
if (i < cols - 1) {
adjacentSpots[1] = mat[i + 1][j];
}
if (j > 0) {
adjacentSpots[2] = mat[i][j - 1];
}
if (j < rows - 1) {
adjacentSpots[3] = mat[i][j + 1];
}
if (thisSpot.type == ' ') {
for (int k = 0; k < 4; k++) {
if (adjacentSpots[k] != null && adjacentSpots[k].distance < (thisSpot.distance - 1)) {
thisSpot.distance = adjacentSpots[k].distance + 1;
thisSpot.closest = adjacentSpots[k];
changeMade = true;
}
}
}
}
}
}
spot spot = endSpot;
while(spot != startSpot) {
moves++;
spot.type = '.';
spot = spot.closest;
}
System.out.println(moves);
}
}
Breadth-first search with backtracking.

Categories

Resources