10/13/2018 BFS

BFS (Breadth First Search)

Starting from a distinguished source vertex, BFS will traverse the graph 'breadth first'. That is, BFS will visit vertices that are direct neighbors of the source vertex (first layer), neighbors of direct neighbors (second layer), and so on, layer by layer. 

 

Idea of Implementation: 

BFS will start with the insertion of the source vertex s into a queue, then processes the queue as follows: take out the front most vertex u from the queue, enqueue all unvisited neighbors of u and mark them as visited. With the help of queue, BFS will visit and all vertices in the connected component that contains s layer by layer. 


import java.util.*;
public class Graph2 {
    private int V; //Number of vertices
    private LinkedList<Integer> adj[]; //adjacency list; array of LinkedList

    public Graph2(int v) {
        V = v;
        adj = new LinkedList[v];
        for (int i = 0; i < v; i++) {
            adj[i] = new LinkedList<>();
        }
    }

    public void addEdge(int v, int w) {
        adj[v].add(w);
    }
    //BFS start with a source
    public void BFS(int s) {
        boolean visited[] = new boolean[V];
        LinkedList<Integer> queue = new LinkedList<Integer>();

        visited[s] = true;
        queue.add(s);

        while (queue.size() != 0) {
            s = queue.poll();
            System.out.println(s + " ");

            Iterator<Integer> i = adj[s].listIterator();
            while (i.hasNext()) {
                int n = i.next();
                if (!visited[n]) {
                    visited[n] = true;
                    queue.add(n);
                }
            }
        }
    }

    public static void main(String args[]) {
        Graph2 g = new Graph2(4);
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 2);
        g.addEdge(2, 0);
        g.addEdge(2, 3);
        g.addEdge(3, 3);

        g.BFS(2); //2 0 3 1
    }
}

Visualization: like an ink in the middle of water, dispersing from the center until making the entire water dark

Application: 用BFS求最短路(迷宫问题)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值