Graph & Search

BFS - Iterative using queue


Breadth First Search or BFS for a Graph

// Java program to print BFS traversal from a given source vertex. 
// BFS(int s) traverses vertices reachable from s. 
import java.util.*; 

// This class represents a directed graph using adjacency list 
// representation 
class Graph 
    private int V; // No. of vertices 
    private LinkedList<Integer> adj[]; //Adjacency Lists 

    // Constructor 
    Graph(int v) 
        V = v; 
        adj = new LinkedList[v]; 
        for (int i=0; i<v; ++i) 
            adj[i] = new LinkedList(); 

    // Function to add an edge into the graph 
    void addEdge(int v,int w) 

    // prints BFS traversal from a given source s 
    void BFS(int s) 
        // Mark all the vertices as not visited(By default 
        // set as false) 
        boolean visited[] = new boolean[V]; 

        // Create a queue for BFS 
        LinkedList<Integer> queue = new LinkedList<Integer>(); 

        // Mark the current node as visited and enqueue it 

        while (queue.size() != 0) 
            // Dequeue a vertex from queue and print it 
            s = queue.poll(); 
            System.out.print(s+" "); 

            // Get all adjacent vertices of the dequeued vertex s 
            // If a adjacent has not been visited, then mark it 
            // visited and enqueue it 
            Iterator<Integer> i = adj[s].listIterator(); 
            while (i.hasNext()) 
                int n =; 
                if (!visited[n]) 
                    visited[n] = true; 

    // Driver method to 
    public static void main(String args[]) 
        Graph g = new Graph(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); 

        System.out.println("Following is Breadth First Traversal "+ 
                        "(starting from vertex 2)"); 

// This code is contributed by Aakash Hasija

Applications of Breadth First Traversal

1) Shortest Path and Minimum Spanning Tree for unweighted graph

In an unweighted graph, the shortest path is the path with least number of edges.

2) Peer to Peer Networks.

In Peer to Peer Networks like BitTorrent, Breadth First Search is used to find all neighbor nodes.

3) Crawlers in Search Engines:

Crawlers build index using Breadth First. The idea is to start from source page and follow all links from source and keep doing same. Depth First Traversal can also be used for crawlers, but the advantage with Breadth First Traversal is, depth or levels of the built tree can be limited.

4) Social Networking Websites:

In social networks, we can find people within a given distance ‘k’ from a person using Breadth First Search till ‘k’ levels.

5) GPS Navigation systems:

Breadth First Search is used to find all neighboring locations.

6) Broadcasting in Network:

In networks, a broadcasted packet follows Breadth First Search to reach all nodes.

7) In Garbage Collection:

Breadth First Search is used in copying garbage collection using Cheney’s algorithm. Refer this and for details. Breadth First Search is preferred over Depth First Search because of better locality of reference:

8) Cycle detection in undirected graph:

In undirected graphs, either Breadth First Search or Depth First Search can be used to detect cycle. In directed graph, only depth first search can be used.

9)Ford–Fulkerson algorithm:

In Ford-Fulkerson algorithm, we can either use Breadth First or Depth First Traversal to find the maximum flow. Breadth First Traversal is preferred as it reduces worst case time complexity to O(VE2).

10)To test if a graph is Bipartite

We can either use Breadth First or Depth First Traversal.

11) Path Finding

We can either use Breadth First or Depth First Traversal to find if there is a path between two vertices.

12) Finding all nodes within one connected component:

We can either use Breadth First or Depth First Traversal to find all nodes reachable from a given node.

Many algorithms like Prim’s Minimum Spanning Tree and Dijkstra’s Single Source Shortest Path use structure similar to Breadth First Search.

DFS - Iterative using stack

DFS - Recursive


深度优先搜索(Depth First Search)

假设初始状态是图中所有顶点均未被访问,则从某个顶点v出发,首先访问该顶点,然后依次从它的各个未被访问的邻接点出发深度优先搜索遍历图,直至图中所有和v有路径相通的顶点都被访问到。 若此时尚有其他顶点未被访问到,则另选一个未被访问的顶点作起始点,重复上述过程,直至图中所有顶点都被访问到为止。

DFS Implementation

Graph Node

public calss GraphNode{
  int val;
  List<GraphNode> neighnors;


HashSet<GraphNode> visited = new HashSet<GraphNode>();

// boolean[][] visited = new boolean[m][n]

Recursive DFS


public void DFS(GraphNode nd){
  //print nd.val
  for(GraphNode next : nd.neighbours){

Non-Recursive DFS


public void DFS(GraphNode start){
  Stack<GraphNode> s = new Stack<GraphNode>();
    GraphNode cur = s.pop();
    //print cur.val
    for(GraphNode next : cur.children){
        visited.add(next);//mark node as visited when adding to stack.
  }//while end

DFS with depth (for Tree)


DFS for binary tree–PreOrder traversal

DFS对于二叉树而言,其遍历序列就是其前序遍历 Pre-order Traversal。

[preorder(node)] = node.val + [preorder(node.left)] + [preorder(node.right)]

DFS 解题框架模板


public static T ans;
public static T path;
public static T problem(){
  ans = new T();
  path = new T();

  dfs(idx ,...); //DFS部分,常用idx作为结果递归的标志
  return ans;
public static void dfs(int idx, ...){
    //handle path 
  path[idx] = true;//递归前假设
  dfs(++idx, ...);//根据不同情况进行处理
  path[idx] = false;//递归后还原

Cycle Detection



  • 未访问过(0)

  • 正在访问其邻居节点(1)

  • 已经访问完毕该节点以及所有该节点可以到达的节点(2)



Topological Sort

Topological Sorting

拓扑排序是一个dfs的应用, 所谓拓扑排序是指在一个DAG(有向无回路图)里给每个节点定义一个顺序(v1…vn), 使得按照这个顺序遍历的节点, 每一个节点vi都是之前遍历过的的节点(v1 ~ vi-1)所指向的(或没有任何其他节点指向的).


Shortest Path and Dijkstra's Algorithm

StackOverflow: What is difference between BFS and Dijkstra's algorithms when looking for shortest path?

Breadth-first search is just Dijkstra's algorithm with all edge weights equal to 1.

Dijkstra's algorithm is conceptually breadth-first search that respects edge costs.

The process for exploring the graph is structurally the same in both cases.

Aos Dabbagh: Understanding Dijkstra's Algorithm

One of Dijkstra’s algorithm modifications on breadth-first search is its use of a priority queue instead of a normal queue. With a priority queue, each task added to the queue has a “priority” and will slot in accordingly into the queue based on its priority level.

UIUC CS473: Breadth First Search, Dijkstra’s Algorithm for Shortest Paths (PDF)


有权图则需要用Dijkstra's Algorithm。


Dijkstra's Algorithm

Last updated