Number of islands
The problem
Given a grid of size N x M (N is the number of rows and M is the number of columns in the grid) consisting of '0's (Water) and ‘1's(Land). Find the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically or diagonally i.e., in all 8 directions.
Input: grid = [ ["1", "1", "1", "0", "1"], ["1", "0", "0", "0", "0"], ["1", "1", "1", "0", "1"], ["0", "0", "0", "1", "1"] ] Output: 2 Explanation: This grid contains 2 islands. Each '1' represents a piece of land, and the islands are formed by connecting adjacent lands horizontally or vertically. Despite some islands having a common edge, they are considered separate islands because there is no land connectivity in any of the eight directions between them. Therefore, the grid contains 2 islands.
Input: grid = [ ["1", "0", "0", "0", "1"], ["0", "1", "0", "1", "0"], ["0", "0", "1", "0", "0"], ["0", "1", "0", "1"," 0"] ] Output: 1 Explanation: In the given grid, there's only one island as all the '1's are connected either horizontally, vertically, or diagonally, forming a single contiguous landmass surrounded by water on all sides.
Input: grid = [ ["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"] ]
· N == grid.length · M == grid[i].length · 1 <= N, M <= 300 · grid[i][j] is '0' or '1'.
cpp
class Solution{
public:
int numIslands(vector<vector<char>> &grid){
}
};java
class Solution {
public int numIslands(char[][] grid) {
}
}python
class Solution:
def numIslands(self, grid):javascript
class Solution {
numIslands(grid) {
}
}csharp
public class Solution {
public int NumIslands(List<List<string>> grid) {
}
}go
func NumIslands(grid [][]byte) int {
}Stuck? Show a way to structure it+
- 01Scan every grid cell and start a traversal whenever an unvisited land cell is found.
- 02Mark the entire connected component using the eight direction offsets required by this version.
- 03Increment the island count once per traversal, not once per land cell.
- 04Explain how in-place marking or a visited matrix prevents repeated work.
Reference answer
Then expect these follow-ups
How would the result differ if only four directions were allowed?
Tests: requirements awareness
How would you process a grid too large to fit in memory?
Tests: scalability reasoning
Hiring now
Linkedin has 196 open roles right now
Also hiring: Paytm
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Software Engineer - Systems and Infrastructure
Mountain View, CA, United States
Staff Software Engineer
Mountain View, CA, United States
Staff Software Engineer, Systems Infrastructure
Bengaluru, KA, India
Next question