200. Number of Islands Leetcode Solution
Number of Islands Leetcode Problem :
Given an m x n 2D binary grid grid which represents a map of ‘1’s (land) and ‘0’s (water), return 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.
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Number of Islands Leetcode Solution :
Constraints :
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] is ‘0’ or ‘1’.
Example 1:
- Input: grid = [
[“1″,”1″,”0″,”0″,”0”],
[“1″,”1″,”0″,”0″,”0”],
[“0″,”0″,”1″,”0″,”0”],
[“0″,”0″,”0″,”1″,”1”]
] - Output: 3
Intuition :
Essentially, you traverse the entire grid and keep track of which “1”‘s you’ve already visited. Each time you find a new unvisited “1”, you will run a recursive DFS search to expand and add all the coordinates of the visited “1”‘s to the visited set.
Approach :
In our DFS function, we will first add our current coordinates to the visited set. Next, we will branch out in all four directions, for each of these next coordinates in four directions, if they are:
- Within the range of the grid
- Equal to “1”
- Never visited before
We can run DFS on these next coordinates. Basically, every time you see an unvisited “1”, we will traverse through the entirety of the island and add all “1”‘s connected to the island to our visited set.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
class Solution { public: void dfs(vector>& grid, int row, int col) { // Base cases for recursion if (row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size() || grid[row][col] != '1') { return; } // Mark the current cell as visited grid[row][col] = '2'; // Recursive calls in 4 directions dfs(grid, row - 1, col); // Up dfs(grid, row + 1, col); // Down dfs(grid, row, col - 1); // Left dfs(grid, row, col + 1); // Right } int numIslands(vector >& grid) { int islandCount = 0; // Traverse each cell in the grid for (int row = 0; row < grid.size(); row++) { for (int col = 0; col < grid[0].size(); col++) { if (grid[row][col] == '1') { islandCount++; dfs(grid, row, col); } } } return islandCount; } };
class Pair{ int first; int second; public Pair(int first,int second){ this.first=first; this.second=second; } } class Pair { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } } class Solution { // Helper function for BFS traversal private void bfs(int row, int col, int[][] visit, char[][] grid) { visit[row][col] = 1; Queueq = new LinkedList (); q.add(new Pair(row, col)); int n = grid.length; int m = grid[0].length; // Define movements: up, right, down, left int[] rowMovement = {-1, 0, 1, 0}; int[] colMovement = {0, 1, 0, -1}; // BFS traversal while (!q.isEmpty()) { int currentRow = q.peek().first; int currentCol = q.peek().second; q.remove(); // Explore all four directions for (int direction = 0; direction < 4; direction++) { int newRow = currentRow + rowMovement[direction]; int newCol = currentCol + colMovement[direction]; // Check if the new position is valid and has '1' if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m && grid[newRow][newCol] == '1' && visit[newRow][newCol] == 0) { // Mark as visited and add to the queue for further exploration visit[newRow][newCol] = 1; q.add(new Pair(newRow, newCol)); } } } } // Main function to count islands public int numIslands(char[][] grid) { int count = 0; int row = grid.length; int column = grid[0].length; int[][] visit = new int[row][column]; // Iterate through each cell in the grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { // If the cell contains '1' and has not been visited, start BFS if (grid[i][j] == '1' && visit[i][j] == 0) { count++; bfs(i, j, visit, grid); } } } // Return the count of islands return count; } }
class Solution: def numIslands(self, grid: List[List[str]]) -> int: output = 0 directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] visited = set() def dfs(curr_x, curr_y): visited.add((curr_x, curr_y)) for dir_x, dir_y in directions: next_x, next_y = curr_x + dir_x, curr_y + dir_y if next_x in range(len(grid)) and next_y in range(len(grid[0])) and grid[next_x][next_y] == "1" and (next_x, next_y) not in visited: dfs(next_x, next_y) for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == "1" and (i, j) not in visited: output += 1 dfs(i, j) return output
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment