Friday, March 11, 2022

Number of Islands

I/P:
8 8 0 0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 0 1 1 1 1 0 1 1 0 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0

O/P: 3




package pep.Day38;

import java.io.*;
import java.util.*;

public class Number_of_Islands {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int m = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
int[][] arr = new int[m][n];

for (int i = 0; i < arr.length; i++) {
String parts = br.readLine();
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = Integer.parseInt(parts.split(" ")[j]);
}
}

// write your code here
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
// pehle check krenge jha pr zero mila vha se dfs call kar denge
// arr[row][col] ko 1 krne ke baad
if (arr[i][j] == 0) {
// jese hi first zero mil jaega count=1ho jaega
count++;
arr[i][j] = 1;
dfs(arr, i, j);
}
}
}

System.out.println(count);
}

// yeh top, left, down, right directions me call hota
// aur jha jha par zero milega usko 1 kr dega
public static void dfs(int[][] arr, int row, int col) {
int[][] dirns = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
for (int[] dir : dirns) {
int x = row + dir[0];
int y = col + dir[1];
if ((x >= 0 && x < arr.length) && (y >= 0 && y < arr[0].length)) {
if (arr[x][y] == 0) {
arr[x][y] = 1;
dfs(arr, x, y);
}
}
}
}

}








No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...