Given N * M string array of O's
and X's
. The task is to find the number of 'X' total shapes. 'X' shape consists of one or more adjacent X's
(diagonals not included)
Here is a simple and easy solution using BFS and Recursion .It execution time is 0.01s.
#include <bits/stdc++.h> using namespace std; vector<pair<int,int>> dir={{0,1},{1,0},{0,-1},{-1,0}}; void BFS(vector< vector<char> > & a,int n,int m,int x,int y) { if(x<0||y<0||x>=n||y>=m) return ; if(a[x][y]!='X') return ; a[x][y]='V'; for(int i=0;i<4;++i) { BFS(a,n,m,dir[i].first+x,dir[i].second+y); } } int main() { //code int t; cin>>t; while(t--) { int n,m; cin>>n>>m; vector< vector<char> > a(n,vector<char>(m)); for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { cin>>a[i][j]; } } int cnt =0; for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { if(a[i][j]=='X') { cnt++; BFS(a,n,m,i,j); } } } cout<<cnt<<endl; } return 0; }