Created
November 12, 2016 15:59
-
-
Save ifndefdeadmau5/484c3367c017a212bc7b5f32b026859d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MAX_VERTEX = 5; | |
const UC = 9999;// Unconnected | |
const data = [ | |
// 1 2 3 4 5 | |
[ 0, 0, 0, 0, 0, 0 ], | |
/*1*/[ 0, 0, 2, 4,UC,UC ], | |
/*2*/[ 0, 2, 0, 1, 3,UC ], | |
/*3*/[ 0, 4, 1, 0,UC, 2 ], | |
/*4*/[ 0,UC, 3,UC, 0, 1 ], | |
/*5*/[ 0,UC,UC, 2, 1, 0 ] | |
]; | |
(function findShortestPath() { | |
function Vertex() { | |
this.isVisited = false; | |
this.Parent = null; | |
this.Distance = 0; | |
} | |
let vertices = []; | |
const start = 1; | |
const end = 0; | |
// Initialize. | |
for (let i = 1; i < MAX_VERTEX + 1; i++) { | |
vertices[i] = new Vertex(); | |
vertices[i].isVisited = false; | |
vertices[i].Parent = start; | |
if (data[start][i] != UC) | |
vertices[i].Distance = data[start][i]; | |
else | |
vertices[i].Distance = UC; | |
} | |
// Dijkstra | |
for (i = start; i < MAX_VERTEX + 1; i++) { | |
minVal = 9999; | |
for (j = 1; j < MAX_VERTEX + 1; j++) { | |
if (!vertices[j].isVisited && vertices[j].Distance != UC) | |
{ | |
if (vertices[j].Distance < minVal) | |
{ | |
minVal = vertices[j].Distance; | |
minIndex = j; | |
} | |
} | |
} | |
// Vertex Select | |
vertices[minIndex].isVisited = true; | |
for (let j = 1; j < MAX_VERTEX + 1; j++) { | |
if (!vertices[j].isVisited && data[minIndex][j] !== UC && data[minIndex][j] !== 0) { | |
if (data[vertices[j].Parent][j] > vertices[minIndex].Distance + data[minIndex][j]) { | |
vertices[j].Distance = vertices[minIndex].Distance + data[minIndex][j]; | |
vertices[j].Parent = minIndex; | |
} | |
} | |
} | |
} | |
console.log(vertices); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment