For this problem, following code is not passing for all the test case(when diagonals are considered).
// { 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
{
//Function to find the number of islands.
public int numIslands(char[][] grid)
{
// Code here
int c=0;
System.out.print(“r=”+grid.length+"\tc="+grid[0].length+"\n");
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[0].length;j++)
{
if(grid[i][j]==‘1’)
{
//System.out.print(“i=”+i+"\tj="+j+"\n");
c++;
findIsland(grid, i, j);
}
}
}
return c;
}
public void findIsland(char[][] grid, int x, int y)
{
int r=grid.length; //4
int c=grid[0].length; //2
if(x<0 || x>=r || y<0 || y>=c || grid[x][y]!=‘1’)
return;
grid[x][y]='2';
System.out.println("x="+x+"\ty="+y+"\n");
findIsland(grid,x,y+1);
findIsland(grid,x,y-1);
findIsland(grid,x+1,y);
findIsland(grid,x-1,y);
findIsland(grid,x-1,y-1);
findIsland(grid,x-1,y+1);
findIsland(grid,x+1,y+1);
findIsland(grid,x-1,y-1);
}
}
failing test case:
Input grid is- 0 1 1 0 1 1 1 0
Expected o/p=1
my output=2
Please. explain what is wring?