并查集提供两种操作:
1.查询a,b是否属于一个集合 bool issamset(V O1,V O2);
2.把a所在集合和b所在集合合并。操作的是元素,合并的是元素所在的集合。union(V O1,V O2);
思路:1.形成所有的样本节点,把所有值为1的位置放入到list中 '5'_'3'
2.每个小样本成一个集合 此时所有的1 是孤零零没有连通的状态
3.连通所有样本点 继续两个for循环
4.返回sizemap的值。
int countIslandsUnion(ivv m)
{
list<string> pAllList;
int row = m.size();
int col = m[0].size();
//1.形成所有的样本节点,把所有值为1的位置放入到list中 '5'_'3'
for (int i=0;i<row;i++)
{
for (int j = 0; j < col;j++)
{
if (m[row][col] == 1)
{
string position = to_string(i) + "_" + to_string(j);
pAllList.push_back(position);
}
}
}
//2.每个小样本成一个集合 此时所有的1 是孤零零没有连通的状态
UnionFindSet<string> * pUnionFindSet=new UnionFindSet<string>(pAllList);
//3.连通所有样本点 继续两个for循环
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (m[i][j] == 1) //每一个位置 它的上下左右位置的值
{
string position = to_string(i) + "_" + to_string(j);
//1.up
if (i - 1 >= 0 && m[i - 1][j] == 1)
{
string up = to_string(i - 1) + "_" + to_string(j);
pUnionFindSet->myunion(up, position);
}
//2.down
if (i + 1 >= 0 && m[i + 1][j] == 1)
{
string down = to_string(i + 1) + "_" + to_string(j);
pUnionFindSet->myunion(down, position);
}
//4.left
if (j - 1 >= 0 && m[i][j - 1] == 1)
{
string left = to_string(i) + "_" + to_string(j - 1);
pUnionFindSet->myunion(left, position);
}
//5.right
if (j - 1 >= 0 && m[i][j + 1] == 1)
{
string right = to_string(i) + "_" + to_string(j + 1);
pUnionFindSet->myunion(right, position);
}
}
}
}
//4.getMembernum pList
//返回sizemap大小
int m_sizemap = pUnionFindSet->getSetNum();
return m_sizemap;
}