Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Count Islands
/** * Count Islands * Given a 2D matrix representing a map, with 1 being path and 0 being water, * find the count of islands. * * @author: Jayesh Chandrapal */ import java.util.*; import java.lang.*; class IslandsCount { int N; public int countIslands() { int count = 0; int[][] matrix = readInput(); for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if(isConnected(i, j, matrix)) { count++; } } } return count; } public boolean isConnected(int i, int j, int[][] matrix) { if(!isValidIndex(i, j, matrix.length)) { return false; } if(matrix[i][j] == 1) { matrix[i][j] = 0; isConnected(i + 1, j, matrix); isConnected(i - 1, j, matrix); isConnected(i, j + 1, matrix); isConnected(i, j - 1, matrix); isConnected(i + 1, j + 1, matrix); isConnected(i + 1, j - 1, matrix); isConnected(i - 1, j - 1, matrix); isConnected(i - 1, j + 1, matrix); return true; } return false; } public boolean isValidIndex(int x, int y, int n) { return !(x < 0 || x >= n || y < 0 || y >= n); } public int[][] readInput() { Scanner in = new Scanner(System.in); N = in.nextInt(); int[][] matrix = new int[N][N]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { matrix[i][j] = in.nextInt(); } } return matrix; } } class Rextester { public static void main(String args[]) { IslandsCount app = new IslandsCount(); System.out.println(app.countIslands()); } }
run
|
edit
|
history
|
help
0
merge sort by java
1a
3e
Decode byte array
variable1
Jumpstatement
Rakibul Haque
Product of Array Except Self
Coding Challenge - 02 (Odd numbers)
MyBirdClass