如图所示:
C#环境下
同一行表示“相互联通”
输入为左边一列,和右边一列,比如左边为 str1[]={“A”,“A”,“C”,“E”,“F”}
最后结果把所有联通的归到一起,
所以输出应当为{{“A”,“B”,“C”,“D”},{“E”,“F”,“G”} }
这个该如何编程?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string[] str1 = { "A", "A", "C", "E", "F" };
string[] str2 = { "B", "C", "D", "F", "G" };
int[] re = { 1, 0, 0, 0, 0, };
int index = 2;
for (int i = 1; i < str1.Length; i++)
{
int st = 0;
for (int j = 0; j <= i-1; j++)
{
if((str1[i]==str1[j]) || (str2[i]==str1[j]) || (str1[i] == str2[j]) || (str2[i]==str2[j]))
{
re[i] = re[j];
st = 1;
break;
}
}
if (st == 0)
{
re[i] = index;
index++;
}
}
List<List<string>> res= new List<List<string>>();
for (int i = 0; i < index-1; i++)
{
res.Add(new List<string>());
}
for (int i = 0; i < str1.Length; i++)
{
if (!res[re[i]-1].Contains(str1[i]))
{
res[re[i] - 1].Add(str1[i]);
}
if (!res[re[i] - 1].Contains(str2[i]))
{
res[re[i] - 1].Add(str2[i]);
}
}
Console.Write("{");
for (int i = 0; i < res.Count; i++)
{
Console.Write("{");
for (int j = 0; j < res[i].Count; j++)
{
Console.Write(res[i][j]);
if (j==res[i].Count-1)
{
break;
}
Console.Write(",");
}
if (i==res.Count-1)
{
Console.Write("}");
}
else
{
Console.Write("},");
}
}
Console.Write('}');
Console.ReadKey();
}
}
}