Two main scenarios of using BFS: do traversal or find the shortest path. Typically, it happens in a tree or a graph.
In some cases, we can abstract a specific question into a tree or a graph. The node will be an actual node or a status while the edge will be an actual edge or a possible transition.
There are two templetes available for dealing BFS.
# Template One
/**
* Return the length of the shortest path between root and target node
*/
int BFS(Node root, Node target) {
Queue<Node> queue = null; // store all nodes which are waiting to be processed
int step = 0; // number of steps needed from root to current node
// initialize
add root to queue
// bfs
while (queue is not empty) {
step = step + 1;
// iterate the nodes which are already in the queue
int size = queue.size();
for (int i = 0; i < size; i++) {
Node cur = the first node in queue;
return cur if cur is target;
for (Node next : the neighbors of cur) {
add next to queue;
}
remove the first node from queue;
}
}
return -1;
}
1. As shown in the code, in each round, the nodes in the queue are the nodes which are waiting to be processed.
2. After each outer while loop, we are one step farther from the root node. The variable step indicates the distance from the root and the current node we are visiting.
Sometimes, it is important to make sure that we never visit a node twice. Otherwise, we might get stuck in an infinite loop, e.g. in graph with cycle. If so, we can add a hash set to the code above to solve this problem.
#Template Two
/**
* Return the length of the shortest path between root and target node
*/
int BFS(Node root, Node target) {
Queue<Node> queue = null; // store all nodes which are waiting to be processed
Set<Node> visited = null; // store all the nodes that we've visited
int step = 0; // number of steps needed from root to current node
// initialize
add root to queue;
add root to visited;
// bfs
while (queue is not empty) {
step = step + 1;
// iterate the nodes which are already in the queue
int size = queue.size();
for (int i = 0; i < size; i++) {
Node cur = the first node in queue;
return cur if cur is target;
for (Node next : the neighbors of cur) {
if (next is not in used){
add next to queue;
add next to visited;
}
}
remove the first node from queue;
}
}
return -1;
}
Exsercise One
Given a 2d grid map of
'1'
s (land) and'0'
s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.Example 1:
Input: 11110 11010 11000 00000 Output: 1Example 2:
Input: 11000 11000 00100 00011 Output: 3