# 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.io.*;
import java.util.*;

// This class represents a directed graph using adjacency list
// representation
class Graph
{
private int V; // No. of vertices

// Constructor
Graph(int v)
{
V = v;
for (int i=0; i<v; ++i)
}

// 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

// Mark the current node as visited and enqueue it
visited[s]=true;

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 = i.next();
if (!visited[n])
{
visited[n] = true;
}
}
}
}

// Driver method to
public static void main(String args[])
{
Graph g = new Graph(4);

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

g.BFS(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]([[http://en.wikipedia.org/wiki/Cheney's_algorithm](http://en.wikipedia.org/wiki/Cheney's_algorithm)](http://en.wikipedia.org/wiki/Cheney's_algorithm](http://en.wikipedia.org/wiki/Cheney's_algorithm))\). Refer this and for details. Breadth First Search is preferred over Depth First Search because of better locality of reference:

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.

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).

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

`以下DFS总结的内容来源：http://chen-tao.github.io/2017/01/26/about-dfs/`

### 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){
if(!visited.contains(next)){
DFS(next);
}
}
}
``````

#### Non-Recursive DFS

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

#### 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;
}
//DFS
public static void dfs(int idx, ...){
if(xxx){//边界条件，递归出口条件
//用当前path内容生成一部分结果集
//handle path
return;
}
//递归处理
path[idx] = true;//递归前假设
dfs(++idx, ...);//根据不同情况进行处理
path[idx] = false;//递归后还原
}
``````

### Cycle Detection

• 未访问过(0)
• 正在访问其邻居节点(1)
• 已经访问完毕该节点以及所有该节点可以到达的节点(2)

## Topological Sort

Topological Sorting

See:

## Shortest Path and Dijkstra's Algorithm

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.

## Reference

Dijkstra's Algorithm