@@ -136,6 +136,7 @@ public class DigraphImpl implements Digraph {
136
136
> 12: 9|
137
137
138
138
### 有向图的可达性
139
+ > 可达性的重要实际应用是在内存管理系统中,一个顶点表示一个对象,一条边表示一个对象的引用。
139
140
``` Java
140
141
public class DirectedDFS {
141
142
private final boolean [] marked;
@@ -175,3 +176,51 @@ public static void main(String[] args) throws FileNotFoundException {
175
176
}
176
177
```
177
178
> 0 1 2 3 4 5 6 8 9 10 11 12
179
+
180
+ ### 单点有向路径
181
+ > 通过DFPath实现
182
+ ``` Java
183
+ public class DepthFirstPathDirectedGraph implements Path {
184
+ private final DigraphImpl g;
185
+ private int s;
186
+ private final boolean [] marked; // Used to mark if current vertex has been accessed.
187
+ private final int [] edgeTo; // Used to save the vertex ahead of current vertex.
188
+ public DepthFirstPathDirectedGraph (DigraphImpl g , int s ){
189
+ this . s = s;
190
+ this . g = (DigraphImpl ) g;
191
+ marked = new boolean [g. V ()];
192
+ edgeTo = new int [g. V ()];
193
+ dfs(g, s);
194
+ }
195
+ public DepthFirstPathDirectedGraph (String file , int s ) throws FileNotFoundException {
196
+ g = new DigraphImpl (new FileInputStream (new File (file)));
197
+ this . s = s;
198
+ marked = new boolean [g. V ()];
199
+ edgeTo = new int [g. V ()];
200
+ dfs(g, s);
201
+ }
202
+ @Override
203
+ public boolean hasPathTo (int v ) {
204
+ return edgeTo[v] != 0 ;
205
+ }
206
+ @Override
207
+ public Iterable<Integer > pathTo (int v ) {
208
+ Bag<Integer > path = new ListBag<Integer > ();
209
+ path. add(v);
210
+ while (edgeTo[v] != s){
211
+ path. add(edgeTo[v]);
212
+ v = edgeTo[v];
213
+ }
214
+ return path;
215
+ }
216
+ private void dfs (DigraphImpl g , int v ){
217
+ marked[v] = true ;
218
+ for (int w : g. adj(v)){
219
+ if (! marked[w]){
220
+ edgeTo[w] = v;
221
+ dfs(g, w);
222
+ }
223
+ }
224
+ }
225
+ }
226
+ ```
0 commit comments