Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save suvashsumon/363e6c28767cf9386420d79b8cf33691 to your computer and use it in GitHub Desktop.
Save suvashsumon/363e6c28767cf9386420d79b8cf33691 to your computer and use it in GitHub Desktop.
A image is given by black and white pixels. We need to the number of white grids.
/*
Sample input :
5 5
WWBWB
WWBWW
BBWWB
WWWBW
WWWBW
Sample Output:
Total white grid : 3
Number of pixels : 4 11 2
*/
#include<bits/stdc++.h>
using namespace std;
int r;
int c;
char arr[1001][1001];
bool visited[1001][1001];
int sum[1001];
bool check(int x, int y)
{
if(x<0 || x>r-1 || y<0 || y>c-1) return false;
if(arr[x][y]=='B') return false;
if(visited[x][y]) return false;
return true;
}
void dfs(int x, int y, int k)
{
visited[x][y] = true;
sum[k]++;
if(check(x-1, y)) dfs(x-1, y, k);
if(check(x, y-1)) dfs(x, y-1, k);
if(check(x+1, y)) dfs(x+1, y, k);
if(check(x,y+1)) dfs(x,y+1, k);
}
int main()
{
cin >> r >> c;
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
cin >> arr[i][j];
}
}
int ans = 0;
int k = 0;
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
if(visited[i][j]==false && arr[i][j]=='W')
{
dfs(i, j, k);
k++;
ans++;
}
}
}
cout << "Total white grid : " << ans << endl;
cout << "Number of pixels : ";
for(int i=0; i<ans; i++) cout << sum[i] << " ";
cout << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment