Cells - Find the number of cells in C++
Find the number of cells
topic description
A rectangular array consisting of the numbers 0 00 to9 99 composition, number1 11 to9 99 represents a cell, and the cell is defined as the same cell along the cell number, up, down, left, and right, if it is still a cell number, find the number of cells in a given rectangular array.
input format
The two integers in the first line represent the matrix size nnn andmmm。
Next nnn lines, each line has a length ofmmm is a string containing only the characters0
to9
, representing thisn × mn \times mn×matrix of m .
output format
One integer per line represents the number of cells.
sample
sample input
4 10
0234500067
1034560500
2045600671
0000000089
sample output
4
hint
Data Size and Conventions
For 100 % 100\%100% data, guarantee1 ≤ n , m ≤ 100 1 \le n,m \le 1001≤n,m≤100。
solution
Just brute force search
the code
#include <bits/stdc++.h>
using namespace std;
short a[1000][1000];
int n,m,s;
string t;
void laiba(int i,int j)
{
if (a[i][j]==0) return;
a[i][j]=0;
laiba(i-1,j);
laiba(i,j-1);
laiba(i+1,j);
laiba(i,j+1);
}
int main ()
{
cin >>n >>m;
for (int i=1;i<=n;i++)
{
cin >>t;
for (int j=1;j<=m;j++)
{
a[i][j]=t[j-1]-48;
}
}
for (int i=1;i<=n;i++)
{
for (int j=1;j<=m;j++)
{
if (a[i][j])
{
s++;
laiba(i,j);
}
}
}
cout <<s;
return 0;
}