Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- import java.math.*;
- /* Name of the class has to be "Main" only if the class is public. */
- class Codechef {
- static StringBuilder str = new StringBuilder("");
- static int l,b;
- static boolean vis[][];
- static boolean isValid(int x,int y)
- {
- return (x>=0&&y>=0&&x<l&&y<b);
- }
- static void dfs(int mat[][],int x,int y)
- {
- vis[x][y]=true;
- if(isValid(x,y+1) && (mat[x][y+1]==1) && (!vis[x][y+1]))
- dfs(mat,x,y+1);
- if(isValid(x,y-1) && (mat[x][y-1]==1) && (!vis[x][y-1]))
- dfs(mat,x,y-1);
- if(isValid(x+1,y) && (mat[x+1][y]==1) && (!vis[x+1][y]))
- dfs(mat,x+1,y);
- if(isValid(x-1,y) && (mat[x-1][y]==1) && (!vis[x-1][y]))
- dfs(mat,x-1,y);
- }
- static void solve(int mat[][])
- {
- vis=new boolean[l][b];
- int ans=0;
- for(int i=0;i<l;i++)
- {
- for(int j=0;j<b;j++)
- {
- if((!vis[i][j]) && mat[i][j]==1)
- {
- ans++;
- dfs(mat,i,j);
- }
- }
- }
- System.out.println(ans);
- }
- public static void main(String[] args) throws java.lang.Exception {
- l=2;
- b=2;
- int mat[][]={{1,0},{0,1}};
- solve(mat);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment