Depth first search and adjacent matrix – Code

Depth first search (DFS) is an algorithm to traverse each element in the data structure. It starts from the source node, which can be root of the tree, or the start of the string, or a cell in matrix. We visit its adjacent node (or children) down the path before visit its other adjacent notes. DFS can be applied to string operations, tree, graph and adjacent matrix. In this post, we focus on depth first search and adjacent matrix only. Adjacent matrix is one representation of graph. Many problem in adjacent matrix uses DFS to solve.

Two examples are introduced to demonstrate depth first search and adjacent matrix: Number of islands and Max region. In both problems, the matrix is a binary matrix with 0s or 1s. The island consists of 1s surrounded by 0s. Number of islands is to count the number of islands in matrix. Sometimes the question is also called “number of shape”. Max Region is to find the islands that has the most count of 1s.

Normally, there are two ways to implement DFS – recursion and stack. In this implementation, we use recursion. There are two methods, wrapper method and helper method. Wrapper method declares variables and call helper method. The helper method is a recursion function. First it checks whether the termination condition is met. Next it checks whether the answer can be found in the pre-defined variables, such as visited. If found, which indicates the node has been visited, we can skip. If not, visit it. Then call itself to visit its 4 (or 8) neighbors.


1. Number of Islands

Facebook Interview Question (CareerCup):
Given a 2d array of 0s and 1s, 0 means water, 1 means land, connected 1s form an island, count the number of islands on this map.
{0, 1, 0, 1, 0}
{0, 1, 0, 0, 1}
{0, 1, 1, 0, 1}
returns 3

Java Code:

Output:
number of islands: 3

O Notation:
Time complexity: O(m*n)
Space complexity: O(m*n)
m is number of rows, n is number of columns


2. Max Region

Goolge Interview Question:
Consider a matrix where each cell contains either a 0 or a 1 and any cell containing a 1 is called a filled cell.
Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally.
Given a matrix, find the number of cells in the largest region in the matrix.
Example:
{1, 1, 0, 0},
{0, 1, 1, 0},
{0, 0, 1, 0},
{1, 0, 0, 0}
Output: 5

Java Code:

Output:
The number of cells in max region is: 5

O Notation:
Time complexity: O(m*n)
Space complexity: O(m*n)

Actionable:
Download DFSAdjacentMatrix.zip
Big O-Notations of DFS and BFS
Shortest path between cells in matrix BFS

Comments are closed