Skip to content

Commit 1a0e398

Browse files
authored
Update Dijkstras-Algorithm.md
1 parent 4b390c2 commit 1a0e398

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Notes/Dijkstras-Algorithm.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,3 +120,43 @@ while ( !visited[ destination ] )
120120
current = index;
121121
}
122122
```
123+
124+
#### Using a priority queue
125+
126+
Remember that as you add items to a priority queue, they are automatically sorted within the queue, so that you are given the "smallest" item when you remove it from the queue.
127+
128+
First, we need to define our `Vertex` class and what attributes it will contain.
129+
130+
```java
131+
// In order for the Vertex class to be sortable, we need to implement the Comparable interface
132+
class Vertex implements Comparable<Vertex>
133+
{
134+
// id - the integer representing the vertex
135+
// dist - the tenetative distance to the vertex
136+
int id, dist;
137+
138+
// neighbors - the integer value of the neighboring vertices
139+
ArrayList<Integer> neighbors;
140+
141+
public Vertex( int id )
142+
{
143+
this.id = id;
144+
this.dist = Integer.MAX_VALUE;
145+
this.neighbors = new ArrayList<Integer>();
146+
}
147+
148+
// This method needs to be overridden to determine how vertices are sorted
149+
public int compareTo( Vertex v )
150+
{
151+
// The vertex that has a smaller tentative distance should be removed from the queue first
152+
if ( this.dist < v.dist )
153+
{
154+
return -1;
155+
}
156+
else
157+
{
158+
return 1;
159+
}
160+
}
161+
}
162+
```

0 commit comments

Comments
 (0)