Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
num Islands
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { public static void main(String args[]) { System.out.println("Hello, World!"); char[][] grid = new char[4][5]; for(int i = 0;i<grid.length;i++){ for(int j = 0;j<grid[i].length;j++){ grid[i][j]='0'; } } grid[0][0] = '1'; grid[0][1] = '1'; grid[0][2] = '1'; grid[0][3] = '1'; grid[1][0] = '1'; grid[1][1] = '1'; grid[1][3] = '1'; grid[2][0] = '1'; grid[2][1] = '1'; System.out.println(numIslands(grid)); } public static int numIslands(char[][] grid) { if(grid==null || grid.length==0) return 0; //go through each element //if it's 1, increment count. //Make it 0 //do bfs on it until 0 comes on all sides. int count = 0; for(int i=0;i<grid.length;i++){ for(int j = 0;j<grid[i].length;j++){ if(grid[i][j]=='1'){ count +=1; //Go DFS DFS(grid,i,j); } } } return count; } public static void DFS(char[][] grid, int row,int col){ int nr = grid.length; int nc = grid[0].length; if(row>nr || row<0 || col>nc || col<0 || grid[row][col]=='0') return; grid[row][col]='0'; DFS(grid,row-1,col); DFS(grid,row+1,col); DFS(grid,row,col-1); DFS(grid,row,col+1); } }
run
|
edit
|
history
|
help
0
Wenfeng Ou
темп
Vasanth Selvaraj
Assignment for Web Software Developer position
rextester.java1
Using Recursion reverse the Line
4a
javaLP
JAVA # Boşluklu bir metinde kaç adet boşluk var
add2