/// <summary> /// 更新连通分量 /// </summary> void UpdateConnectComponent() { //算法思路 //1. 按行扫描 //2. 找到可行的结点 //3. 查看该可行结点的左下邻居是否有islandId,有则用该id,没有则新建一个id //4. 如果邻居的id不同,则随意用其中一个,并把这些不同的id标记为相同 m_unionFind.Clear(); short ccCount = 1; for (int x = 0; x < m_widthCount; x++) { for (int y = 0; y < m_heightCount; y++) { if (m_map[x][y] == c_obstacle) { continue; } short leftValue = 0; short downValue = 0; int left = x - 1; if (left >= 0) { if (m_map[left][y] != c_obstacle) { leftValue = m_map[left][y]; } } int down = y - 1; if (down >= 0) { if (m_map[x][down] != c_obstacle) { downValue = m_map[x][down]; } } if (leftValue == 0 && downValue == 0) { m_map[x][y] = ccCount++; } else if (leftValue == 0 && downValue != 0) { m_map[x][y] = downValue; } else if (leftValue != 0 && downValue == 0) { m_map[x][y] = leftValue; } else { m_map[x][y] = leftValue; m_unionFind.Union(leftValue, downValue); } } } }