#include <iostream>
#include <fstream>
using namespace std;
struct Number
{
int i;
int j;
int num;
struct Number *next;
};
int SearchNumber(int i,int j, int l, struct Number *phead);
void ClearFunction(struct Number *phead);
int main()
{
int m;
int n;
int x;
int y;
int a;
int i;
int j;
int s = 0;
int l = 1;
int total = 0;
struct Number *phead;
struct Number *ptail;
struct Number *pnew;
struct Number *p;
pnew = phead = ptail = NULL;
ifstream infile("Number.txt",ios::in);
if (!infile)
{
cerr << "打開文件失敗!" << endl;
exit(1);
}
cout << "請輸入矩陣的行數和列數:" << endl;
cin >> m >> n;
for (x=0; x<m; x++)
{
for (y=0; y<n; y++)
{
pnew = (struct Number *)malloc(sizeof (struct Number));
pnew->i = x;
pnew->j = y;
infile >> pnew->num;
cout << pnew->num << " ";
pnew->next = NULL;
if (phead == NULL)
{
phead = pnew;
ptail = pnew;
}
else
{
ptail->next = pnew;
ptail = pnew;
}
}
cout << endl;
}
int *count = new int[sizeof(int)*m*n];
for (i=0; i<m*n; i++)
{
count [i] = 0;
}
p = phead;
while (p != NULL)
{
if (p->num == 1)
{
total ++;
}
p = p->next;
}
while (phead != NULL)
{
if (phead->num == 1)
{
s++;
i = phead->i;
j = phead->j;
count[s] = SearchNumber(i,j,l,phead);
}
phead = phead->next;
}
cout << endl;
cout << "數字1的連通區域的個數為:" << s << endl;
cout << "各個區域中含有1的個數為:";
for (a=1; a<=s; a++)
{
cout << count[a] << " ";
}
cout << endl;
cout << "個連通區域中1的總個數為:" << total << endl;
cout << endl;
system("pause");
ClearFunction(phead);
delete[] count;
return 0;
}
int SearchNumber(int i, int j, int l, struct Number *phead)
{
while (phead!=NULL)
{
if ((phead->i == i+1)&&(phead->j == j))
{
if (phead->num == 1)
{
phead->num = 2;
l++;
l = SearchNumber(i+1,j,l,phead);
}
}
if ((phead->i == i-1)&&(phead->j == j))
{
if (phead->num == 1)
{
phead->num = 2;
l++;
l = SearchNumber(i-1,j,l,phead);
}
}
if ((phead->i == i)&&(phead->j == j+1))
{
if (phead->num == 1)
{
phead->num = 2;
l++;
l = SearchNumber(i,j+1,l,phead);
}
}
if ((phead->i == i+1)&&(phead->j == j))
{
if (phead->num == 1)
{
phead->num = 2;
l++;
l = SearchNumber(i,j-1,l,phead);
}
}
phead = phead->next;
}
return l;
}
void ClearFunction(struct Number *phead)
{
struct Number *p;
while (phead!=NULL)
{
p = phead;
phead = p->next;
free(p);
}
}