题目内容:
现有画有黑线(直线或曲线)的白底图片一张,计算出有多少条黑线、并依次输出每条黑线所占的点数。图片我们用0、1图表示,1代表黑点 0 代表白点,某点周围8个方向都算连通,如下图所示,共有3条黑线,长度分别是5、3、5:
1 0 0 0 0 0 0
0 1 1 1 1 0 0
0 0 0 0 0 0 0
1 1 0 0 0 1 1
1 0 0 1 1 1 0
输入描述
图的宽w、高h,换行输入图的像素点.(测试数据结果唯一确定)
输出描述
黑线条数、换行输出每条线长度.(条数及每个长度各占一行).
输入样例
7 5
1 0 0 0 0 0 0
0 1 1 1 1 0 0
0 0 0 0 0 0 0
1 1 0 0 0 1 1
1 0 0 1 1 1 0
输出样例
3
5
3
5
*/
//思路:广搜
#include <iostream>
#include <queue>
using namespace std;
int a[100][100];
int n, m;
typedef struct node{
int x;
int y;
}Node;
int b[9][2] = {-1, -1, -1, 0, -1, 1, 0, -1, 0, 1, 1, -1, 1, 0, 1, 1};
int wf(int x, int y){
queue<Node> point;
Node n1, n2, n3;
if(a[x][y] == 0)
return 0;
int count = 0;
int yy, xx;
n1.x = x; n1.y = y;
point.push(n1);
while(point.empty() != 1){
n2 = point.front();
a[n2.x][n2.y] = 0;
point.pop();
count++;
for(int i = 0; i < 8; i++){
xx = n2.x + b[i][0];
yy = n2.y + b[i][1];
if(xx < n && xx >= 0 && yy < m && yy >= 0){
int temp = 0;
temp = a[xx][yy];
if(a[xx][yy] == 1)
{
n3.x = xx; n3.y = yy;
a[xx][yy] = 0; //必须清零,否则前一个广搜时会重复
point.push(n3);
}
}
}
}
return count;
}
int main(){
int xian = 0;
int b[100];
cin >> m >> n;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
cin >> a[i][j];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(a[i][j] == 1){
int t = wf(i, j);
b[xian++] = t;
}
}
}
cout << xian << endl;
for(int i = 0; i < xian; i++){
cout << b[i] << endl;
}
return 0;
}