You are given a 2D matrix consisting of the following:
1: land
0: water
Considering N-8 neighbourhood, your task is to find the number of islands in the given landscape.
Assume that the the 2D matrix is surrounded by water beyond the boundaries.
Definitions:
N-8 neighbourhood: 2 cells are considered neighbours, if they share an edge or a corner.
Island: A piece of connected land surrounded by water.
Input Format
First line of input contains T – number of test cases. The first line of each test case contains R, C – the size of the matrix. Its followed by a matrix of size RxC, consisting only of 0s and 1s.
Constraints
1 <= T <= 100
1 <= R,C <= 500
Output Format
For each test case, print the total number of islands, separated by new line.
Input | Output |
---|---|
3 4 8 01001101 10001010 00100100 01101101 6 1 0 1 0 0 1 1 9 5 00000 10001 00110 01100 10000 00000 00101 00011 00110 | 4 2 3 |
import java.util.Scanner;
public class Main {
public static int Solution(char[][] array){
int result = 0;
for(int i=0; i<array.length; ++i){
for(int j=0; j<array[0].length; ++j){
if(array[i][j] == '1'){
dfs(array, i, j);
++result;
}
}
}
return result;
}
public static void dfs(char[][] island, int i, int j){
if(i<0 || i>=island.length || j<0 || j>=island[0].length)
return;
if(island[i][j] != '1')
return;
island[i][j] = '2';
// Checking all the 8 directions..
dfs(island, i-1, j-1);
dfs(island, i-1, j);
dfs(island, i-1, j+1);
dfs(island, i, j-1);
dfs(island, i, j+1);
dfs(island, i+1, j-1);
dfs(island, i+1, j);
dfs(island, i+1, j+1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int test_cases = sc.nextInt();
while(test_cases-->0){
int rows = sc.nextInt();
int columns = sc.nextInt();
char[][] matrix = new char[rows][columns];
for(int i=0; i<matrix.length; i++){
String input = sc.next();
for(int j=0; j<matrix[0].length; j++){
matrix[i][j] = input.charAt(j);
}
}
int values = Solution(matrix);
System.out.println(values);
}
}
}