Yesterday I solved a few hands-on coding problems using Java programming language.
I came across this easy problem(called Medium there) over GfG, to turn on the inertia:
Problem: Find the Number of Islands
Problem Description: https://practice.geeksforgeeks.org/problems/find-the-number-of-islands
Problem Approach: DFS
Time Complexity: O(V) where v = number of cells in the input grid
One Java Solution:
// { Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while(T-->0)
{
String[] s = br.readLine().trim().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++){
String[] S = br.readLine().trim().split(" ");
for(int j = 0; j < m; j++){
grid[i][j] = S[j].charAt(0);
}
}
Solution obj = new Solution();
int ans = obj.numIslands(grid);
System.out.println(ans);
}
}
}// } Driver Code Ends
class Solution
{
int r, c;
byte[] xOffset = {1, 1, 1, 0, -1, -1, -1, 0};
byte[] yOffset = {1, 0, -1, -1, -1, 0, 1, 1};
//Function to find the number of islands.
public int numIslands(char[][] grid)
{
// Code here
r = grid.length;
c = grid[0].length;
boolean[][] visited = new boolean[r][c];
int cnt = 0;
for (int i=0; i<r; i++) {
for(int j=0; j<c; j++) {
if (grid[i][j]=='1' && !visited[i][j]) {
dfs(grid, visited, i, j);
cnt++;
}
}
}
return cnt;
}
private void dfs (char[][] grid, boolean[][] visited, int x, int y) {
//input validation
if (!valid (grid, x, y) || visited[x][y]==true) {
return;
}
visited[x][y] = true;
for (int i=0; i<8; i++) {
int newX = x + xOffset[i];
int newY = y + yOffset[i];
if(valid(grid, newX, newY) && !visited[newX][newY]) {
dfs(grid, visited, newX, newY);
}
}
}
boolean valid (char[][]grid, int x, int y) {
if (x<0 || x>=r || y<0 || y>=c || grid[x][y] == '0'){
return false;
}
return true;
}
}
Do share your thoughts and feel free to talk about the alternatives/optimisations you feel can be done in the comment section!
Love! ❤️
#Lets #Code
Follow us on :
https://twitter.com/ThinkAlgorithms
https://www.facebook.com/theAlgorithmicCoder