DFS和BFS(無向圖)Java實現

來源:互聯網
上載者:User

標籤:.com   父節點   style   pos   nbsp   src   存在   gre   search   

package practice;import java.util.Iterator;import java.util.Stack;import edu.princeton.cs.algs4.*;public class TestMain {    public static void main(String[] args) {        Graph a = new Graph(6);        a.addEdge(2, 4);        a.addEdge(2, 3);        a.addEdge(1, 2);        a.addEdge(0, 5);        a.addEdge(0, 1);        a.addEdge(0, 2);        a.addEdge(3, 4);        a.addEdge(3, 5);        System.out.println(a);                DisposeMap df = new DisposeMap(a);        /*df.dfs(0);        System.out.println(df.hasPathTo(1));        System.out.println(df.hasPathTo(2));        Stack<Integer> aStack = df.pathTo(1);        while (!aStack.isEmpty()) {            System.out.print(aStack.pop() + "->");        }        System.out.println("end");*/                df.bfs(0);        for (int i = 0; i < 6; i++) {            System.out.println(df.marked(i));        }        Stack<Integer> aStack = df.pathTo(4);        while (!aStack.isEmpty()) {            System.out.print(aStack.pop() + "->");        }        System.out.println("end");    }}/* * 圖處理dispose */class DisposeMap {    private boolean[] marked; //將已經搜素過的節點儲存為true    private int count = 0;    private Graph G;    private int s; //起點    private int[] edgeTo; //edgeTo[w] = v,w為圖中的節點,v為它的父節點        public DisposeMap(Graph G) {        this.G = G;                marked = new boolean[G.V];        edgeTo = new int[G.V];        for (int i = 0; i < marked.length; i++) {            marked[i] = false;        }    }    /*     * 深度優先搜尋,儲存以s為起點所能到達的所有點     */    public void dfs(int s) {        marked[s] = true;            count++;        System.out.println("Search" + s);        for (Integer b : G.adj(s)) { //搜尋一個節點的相鄰的第一個沒有被標記過的節點            if (marked[b] == false) { //如果沒有搜尋過這個節點,就搜尋它                edgeTo[b] = s;                dfs(b);            }        }    }    /*     * 廣度優先搜尋     */    public void bfs(int s) {        edu.princeton.cs.algs4.Queue<Integer> queue = new Queue<Integer>();        queue.enqueue(s);        marked[s] = true;                while (!queue.isEmpty()) {            Integer temp = queue.dequeue();            for (Integer b : G.adj(temp)) { //搜尋一個節點的所有的相鄰的節點                if (marked[b] == false) { //如果沒有搜尋過這個節點,就搜尋它                    queue.enqueue(b);                    edgeTo[b] = temp;                    marked[b] = true;                                    }            }        }    }    /*     * 查看某點是否被標記     */    public boolean marked(int w) { return marked[w];}    /*     * 搜尋了幾個點     */    public int count() { return count;}    /*     * 是否存在s到v的路徑     */    public boolean hasPathTo(int v) {        return marked(v);    }    /*     * s到v的路徑,有則返回一個Stack,沒有則返回null     */    public Stack<Integer> pathTo(int v) {        Stack<Integer> a = new Stack<Integer>();        for (int i = v; i != s; i = edgeTo[i])             a.push(i);        a.push(s);        return a;    }}/* * 圖 */class Graph {    Bag<Integer>[] graph; //這裡使用背包的數組,鄰借表    int V;    int E;        public Graph(int V) {        this.V = V;        graph = (Bag<Integer>[]) new Bag[V];        for (int i = 0; i < graph.length; i++) {            graph[i] = (Bag<Integer>) new Bag();        }    }    /*     * 返回頂點數     */    public int V() { return V;}    /*     * 返回邊數     */    public int E() { return E;}    /*     * 向圖中添加一條邊     */    public void addEdge(int v, int w) {        graph[v].add(w);        graph[w].add(v);        E++;    }    /*     * 和v相鄰的所有頂點     */    public Iterable<Integer> adj(int v) {        return graph[v];    }    /*     * 計算v的度數     */    public static int degree(Graph G, int v) {        int degree = 0;        for (Integer bag : G.graph[v]) degree++;        return degree;    }    @Override    public String toString() {        String s = V + " vertices, " + E + " edges\n";        for (int v = 0; v < V; v++) {            s += v + ": ";            for (Integer integer : this.adj(v)) {                s += integer + " ";            }            s += "\n";        }        return s;    }}/* * 背包 */class Bag<T> implements Iterable<T> {    Node first;        private class Node {        T value;        Node next;    }        public void add(T value) {        Node oldfirst = first;        first = new Node();        first.value = value;        first.next = oldfirst;    }        public void delete(T value) {            }        @Override    public Iterator<T> iterator() {        return new BagIterator();    }        private class BagIterator implements Iterator<T> {        Node node = first;                @Override        public boolean hasNext() {            return node != null;        }        @Override        public T next() {            T tempt = node.value;            node = node.next;            return tempt;        }    }}

代碼中的無向圖

 

圖的儲存-鄰接表

 

DFS和BFS(無向圖)Java實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.