Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class PathFinder {
- public static void main(String[] args) {
- int[][] tab = { // the example from the topic
- {0, 7, 2, 0, 0, 0},
- {0, 0, 2, 1, 0, 0},
- {0, 3, 0, 8, 5, 0},
- {0, 0, 0, 0, 4, 3},
- {0, 0, 0, 5, 0, 1},
- {0, 0, 0, 0, 0, 0}
- };
- System.out.println(getShortestPath(tab, 1, 6));
- }
- public static int getShortestPath(int [][] tab,int source,int destination) {
- int sourceIndex = source - 1;
- int destinationIndex = destination - 1;
- final int noNodes = tab.length;
- Node[] nodesTab = new Node[noNodes];
- for (int i = 0; i < noNodes; i++) {
- nodesTab[i] = new Node();
- }
- nodesTab[sourceIndex].setWeight(0); // because nodesTab[0] is the source node
- nodesTab[sourceIndex].setVisited(true);
- int parentNode = 0, childNode = 0;
- while (parentNode != destinationIndex) {
- for (int i = 0; i < tab[parentNode].length; i++) {
- if (tab[parentNode][i] != 0) {
- childNode = i;
- int weightFromSourceToChild = (nodesTab[parentNode].getWeight() + tab[parentNode][childNode]);
- if (!nodesTab[childNode].isVisited() &&
- weightFromSourceToChild < nodesTab[childNode].getWeight()
- || nodesTab[childNode].getWeight() == -1) {
- nodesTab[childNode].setVisited(true);
- nodesTab[childNode].setWeight(weightFromSourceToChild);
- }
- }
- }
- parentNode = childNode;
- }
- int shortestPath = nodesTab[destinationIndex].getWeight();
- return shortestPath;
- }
- }
- class Node {
- private int weight;
- private boolean visited;
- public Node() {
- setWeight(-1);
- setVisited(false);
- }
- public int getWeight() {
- return this.weight;
- }
- public void setWeight(int weight) {
- this.weight = weight;
- }
- public boolean isVisited() {
- return this.visited;
- }
- public void setVisited(boolean visited) {
- this.visited = visited;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement