We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<bits/stdc++.h>usingnamespacestd;#define ROW 10#define COL 10intn,m;intgrid[ROW][COL];boolvis[ROW][COL];intans=0;// Direction vectorsvector<vector<int>>dir{{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};// Function to check if a cell is be visited or notboolisValid(boolvis[][COL],introw,intcol){if(row<0||row>=ROW||col<0||col>=COL)returnfalse;if(vis[row][col])returnfalse;returntrue;}// Function to perform the BFSvoidBFS(intgrid[][COL],boolvis[][COL],introw,intcol){inttem=0;queue<pair<int,int>>q;q.push({row,col});vis[row][col]=true;while(!q.empty()){pair<int,int>fro=q.front();intx=fro.first;inty=fro.second;q.pop();tem++;for(autod:dir){intneix=x+d[0];intneiy=y+d[1];if(isValid(vis,neix,neiy)&&grid[neix][neiy]){q.push({neix,neiy});vis[neix][neiy]=true;grid[neix][neiy]=0;}}}ans=max(ans,tem);}// Driver codeintmain(){cin>>n>>m;for(inti=0;i<n;i++)for(intj=0;j<m;j++)cin>>grid[i][j];memset(vis,false,sizeof(vis));for(inti=0;i<n;i++)for(intj=0;j<m;j++)if(grid[i][j])BFS(grid,vis,i,j);cout<<ans;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Connected Cells in a Grid
You are viewing a single comment's thread. Return to all comments →
BFS