110,561
社区成员
发帖
与我相关
我的任务
分享
private void btnCalc_Click(object sender, EventArgs e)
{
//将字符串数据读取到数组fzArr中
string[] strfzArr = txtArr.Text.Split('\n');
List<string> strfzList = new List<string>();
string strlinetrim;
//总人数
int peopleCnt;
string[] strlineArr;
foreach (string strline in strfzArr)
{
strlinetrim = strline.Trim();
if (strlinetrim.Length > 0)
{
strfzList.Add(strlinetrim);
}
}
peopleCnt = strfzList.Count;
//方针数组
bool[,] fzArr = new bool[peopleCnt, peopleCnt];
//每个人属于群的序号(从1开始)
int[] rqIndex = new int[peopleCnt];
//每个序号是否被使用
bool[] indexUseflag = new bool[peopleCnt + 1];
//人群数
int rqCnt = 0;
//支持两种格式的输入
//输入方式1:数字间没有空格
if (strfzList[0].Length == peopleCnt)
{
for (int i = 0; i < peopleCnt; i++)
{
for (int j = 0; j < strfzList[i].Length && j < peopleCnt; j++)
{
fzArr[i, j] = strfzList[i][j] != 48; //字符'0'的Ascii码为48
}
}
}
//输入方式2:数字间有空格
else
{
for (int i = 0; i < peopleCnt; i++)
{
strlineArr = strfzList[i].Split(' ');
for (int j = 0; j < strlineArr.Length && j < peopleCnt; j++)
{
fzArr[i, j] = Convert.ToInt32(strlineArr[j]) != 0;
}
}
}
//开始计算
//群的序号(从1开始)
int lei = 0;
int temp;
for (int i = 0; i < peopleCnt; i++)
{
for (int j = i + 1; j < peopleCnt; j++)
{
if (fzArr[i, j])
{
if (rqIndex[i] == 0 && rqIndex[j] == 0)
{
rqIndex[j] = rqIndex[i] = ++lei;
}
else if (rqIndex[i] == 0)
{
rqIndex[i] = rqIndex[j];
}
else if (rqIndex[j] == 0)
{
rqIndex[j] = rqIndex[i];
}
else
{
if (rqIndex[i] > rqIndex[j])
{
temp = rqIndex[i];
for (int k = 0; k < rqIndex.Length; k++)
{
if (rqIndex[k] == temp)
rqIndex[k] = rqIndex[j];
}
}
else if (rqIndex[j] > rqIndex[i])
{
temp = rqIndex[j];
for (int k = 0; k < rqIndex.Length; k++)
{
if (rqIndex[k] == temp)
rqIndex[k] = rqIndex[i];
}
}
}
}
else
{
if (rqIndex[i] == 0)
rqIndex[i] = ++lei;
if (rqIndex[j] == 0)
rqIndex[j] = ++lei;
}
}
}
foreach (int rqIndex1 in rqIndex)
{
if (!indexUseflag[rqIndex1])
{
indexUseflag[rqIndex1] = true;
rqCnt++;
}
}
MessageBox.Show(rqCnt.ToString());
}
个人习惯:不喜欢用控制台做,喜欢用Winform做
本程序中不需要手动输入人数,程序会通过矩阵大小判断人数
运行结果: