794. Count Islands Using DFS Recursion

MediumRecursionRecursion

Given an m x n binary grid where 1 represents land and 0 represents water, return the number of islands. An island is a group of 1s connected 4-directionally (up, down, left, right). You must count the islands using recursive DFS. Input is a JSON 2D array of 0s and 1s.

Input: A JSON 2D integer array of 0/1.

Output: Return an integer — the island count.

Examples

Example 1
Input: [[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]]
Output: 1
Explanation: All 1s are connected into one island.
Example 2
Input: [[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]
Output: 3
Explanation: Three separate connected components of 1s.
Example 3
Input: [[0,0,0],[0,0,0]]
Output: 0
Explanation: No land cells.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →