图深度优先路径  Depth-first search to find paths in a graph_graph

* DepthFirstPaths.java

package com.merrytech;

import java.util.HashMap;
import java.util.Stack;

public class DepthFirstPaths<E> {
    private final HashMap<E, Boolean> marked; // Has dfs() been called for the vertex?
    private final HashMap<E, E> edgeTo;       // last vertex on known path to this vertex
    private final E s;                  // source

    public DepthFirstPaths(Graph<E> g, E s) {
        this.marked = new HashMap<>();
        for (E e : g.getVertices()) {
            this.marked.put(e, false);
        }
        this.edgeTo = new HashMap<>();
        this.s = s;
        dfs(g, s);
    }

    private void dfs(Graph<E> g, E v) {
        this.marked.put(v, true);
        for (E w : g.getAdjList(v)) {
            if (!this.marked.get(w)) {
                this.edgeTo.put(w, v);
                dfs(g, w);
            }
        }
    }

    public boolean hasPathTo(E v) {return this.marked.get(v);}

    /**
     * Depth-first search to find paths in a graph
     * @param v E
     * @return Iterable<E>
     */
    public Iterable<E> pathTo(E v) {
        if (!hasPathTo(v)) {return null;}
        Stack<E> path = new Stack<E>();
        for (E x = v; !x.equals(this.s); x = this.edgeTo.get(x)) {
            path.push(x);
        }
        path.push(this.s);
        return path;
    }
}

* Graph.java

package com.merrytech;

import java.util.*;

public class Graph<E> {
    private final int v; // number of vertices
    private int e; // number of edges
    private final HashMap<E, LinkedList<E>> adj; // adjacency lists

    public Graph(int v) {
        this.v = v;
        this.e = 0;
        this.adj = new HashMap<>(v);
    }

    public int countV() { return this.v; }
    public int countE() { return this.e; }

    public void addEdge(E v, E w) {
        if (!this.adj.containsKey(v)) {
            this.adj.put(v, new LinkedList<E>());
        }
        if (!this.adj.containsKey(w)) {
            this.adj.put(w, new LinkedList<E>());
        }
        this.adj.get(v).add(w);
        this.adj.get(w).add(v);
        this.e += 1;
    }

    public List<E> getAdjList(E v) { return this.adj.get(v); }
    public Set<E> getVertices() { return this.adj.keySet(); }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(this.v).append(" vertices, ").append(this.e).append(" edges\n");
        for (Map.Entry<E, LinkedList<E>> entry : this.adj.entrySet()) {
            sb.append(entry.getKey().toString()).append(": ");
            for (E w : entry.getValue()) {
                sb.append(w.toString()).append(" ");
            }
            sb.append("\n");
        }
        return sb.toString();
    }
}

* Main.java

package com.merrytech;

import java.util.Iterator;

public class Main {

    public static void main(String[] args) {
        Graph<Integer> graph = new Graph<>(6);
        graph.addEdge(0, 2);
        graph.addEdge(0, 1);
        graph.addEdge(1, 2);
        graph.addEdge(3, 5);
        graph.addEdge(3, 4);
        graph.addEdge(3, 2);
        graph.addEdge(2, 4);
        graph.addEdge(5, 0);
        System.out.println(graph.toString());

        DepthFirstPaths<Integer> dfp = new DepthFirstPaths<>(graph, 0);
        Iterable<Integer> path = dfp.pathTo(5);
        Iterator<Integer> it = path.iterator();
        System.out.printf("%d", it.next());
        while (it.hasNext()) {
            System.out.printf("-%d", it.next());
        }
        System.out.println();
    }
}

图深度优先路径  Depth-first search to find paths in a graph_无向图_02

上一篇: 无向图创建 Undirected Graphs, 深度优先 DFS DepthFirstSearch