Ganesh1648

Cars

Aug 9th, 2020
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.*;
  3. import java.math.*;
  4.  
  5. /* Name of the class has to be "Main" only if the class is public. */
  6. class Codechef {
  7.  
  8.   static StringBuilder str = new StringBuilder("");
  9.   static int l,b;
  10.   static boolean vis[][];
  11.  
  12.     static boolean isValid(int x,int y)
  13.     {
  14.         return (x>=0&&y>=0&&x<l&&y<b);
  15.     }
  16.    
  17.     static void dfs(int mat[][],int x,int y)
  18.     {
  19.         vis[x][y]=true;
  20.         if(isValid(x,y+1) && (mat[x][y+1]==1) && (!vis[x][y+1]))
  21.             dfs(mat,x,y+1);
  22.         if(isValid(x,y-1) && (mat[x][y-1]==1) && (!vis[x][y-1]))
  23.             dfs(mat,x,y-1);
  24.         if(isValid(x+1,y) && (mat[x+1][y]==1) && (!vis[x+1][y]))
  25.             dfs(mat,x+1,y);
  26.         if(isValid(x-1,y) && (mat[x-1][y]==1) && (!vis[x-1][y]))
  27.             dfs(mat,x-1,y);
  28.     }
  29.    
  30.     static void solve(int mat[][])
  31.     {
  32.         vis=new boolean[l][b];
  33.         int ans=0;
  34.         for(int i=0;i<l;i++)
  35.         {
  36.             for(int j=0;j<b;j++)
  37.             {
  38.                 if((!vis[i][j]) && mat[i][j]==1)
  39.                 {
  40.                     ans++;
  41.                     dfs(mat,i,j);
  42.                 }
  43.             }
  44.         }
  45.         System.out.println(ans);
  46.     }
  47.  
  48.   public static void main(String[] args) throws java.lang.Exception {
  49.    
  50.     l=2;
  51.     b=2;
  52.     int mat[][]={{1,0},{0,1}};
  53.     solve(mat);
  54.   }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment