@@ -94,20 +94,20 @@ _Cons_
94
94
95
95
Rather than making space for all _ N_ x _ N_ possible edge connections, an _ adjacency list_ keeps track of the vertices that a vertex has an edge to.
96
96
97
- We are able to do this by creating an ` ArrayList ` that contains ` ArrayLists ` holding the values of the vertices that a vertex is connected to.
97
+ We are able to do this by creating an array that contains ` ArrayLists ` holding the values of the vertices that a vertex is connected to.
98
98
99
99
``` java
100
- ArrayList<ArrayList< Integer >> graph = new ArrayList<ArrayList< Integer >> () ;
100
+ ArrayList<Integer > [] graph = new ArrayList<Integer>[ N + 1 ] ;
101
101
102
102
// For each vertex, we need to initialize the list of vertices the vertex has a connection to
103
103
for ( int i = 0 ; i <= N ; i++ )
104
104
{
105
- graph. add( new ArrayList<Integer > () );
105
+ graph[ i ] = new ArrayList<Integer > ();
106
106
}
107
107
108
- graph. get( i ) . add( j ); // get the list of vertices for vertex i and add a connection to vertex j
108
+ graph[ i ] . add( j ); // get the list of vertices for vertex i and add a connection to vertex j
109
109
110
- ArrayList<Integer > neighbors = graph. get( k ) ; // get the list of vertices that vertex k is connected to
110
+ ArrayList<Integer > neighbors = graph[ k ] ; // get the list of vertices that vertex k is connected to
111
111
```
112
112
113
113
#### Pros and Cons
@@ -168,7 +168,7 @@ In order to do this, we will be using a _Queue_ since it follows the "_first in,
168
168
// Get the current vertex
169
169
Integer current = queue. remove();
170
170
// Get the current vertex's neighbors
171
- List <Integer > neighbors = graph. get( current ) ;
171
+ ArrayList <Integer > neighbors = graph[ current ] ;
172
172
173
173
// For each of the current vertex's neighbors...
174
174
foreach ( Integer neighbor : neighbors )
@@ -225,7 +225,7 @@ Since a _Stack_ follows the "_last in, first out_" ordering, when we are adding
225
225
// Get the current vertex
226
226
Integer current = stack. pop();
227
227
// Get the current vertex's neighbors
228
- List <Integer > neighbors = graph. get( current ) ;
228
+ ArrayList <Integer > neighbors = graph[ current ] ;
229
229
230
230
// For each of the current vertex's neighbors...
231
231
foreach ( Integer neighbor : neighbors )
0 commit comments