这道题目是思路是图的遍历。
图的遍历可以深度优先和广度优先遍历两种,本答案使用了深度优先遍历算法
#include<iostream>
#include<string>
using namespace std;
int a[100][100] = { 0 };
int book[100] = { 0 };
int n = 0;
void search(int num,int index)
{
if (n == index)
return;
for (int i = 0; i <= index; i++)
{
if (a[i][num] == 1)
{
n++;
book[i] = 1;
search(i, index);
n--;
}
}
for (int i = 0; i <= index; i++)
{
if (a[num][i] == 1)
{
n++;
book[i] = 1;
search(i, index);
n--;
}
}
}
int main()
{
int x, y;
int index = 0;
cin >> x >> y;
if (x != 0 && y != 0)
a[x][y] = 1;
index++;
while (x != 0 && y != 0)
{
cin >> x >> y;
if (x != 0 && y != 0)
{
a[x][y] = 1;
index++;
}
}
search(1, index);
int count = 0;
for (int i = 0; i <= index; i++)
{
if (book[i] == 1 && i != 1)
count++;
}
cout << count << endl;
//system("pause");
}
#include<string>
using namespace std;
int a[100][100] = { 0 };
int book[100] = { 0 };
int n = 0;
void search(int num,int index)
{
if (n == index)
return;
for (int i = 0; i <= index; i++)
{
if (a[i][num] == 1)
{
n++;
book[i] = 1;
search(i, index);
n--;
}
}
for (int i = 0; i <= index; i++)
{
if (a[num][i] == 1)
{
n++;
book[i] = 1;
search(i, index);
n--;
}
}
}
int main()
{
int x, y;
int index = 0;
cin >> x >> y;
if (x != 0 && y != 0)
a[x][y] = 1;
index++;
while (x != 0 && y != 0)
{
cin >> x >> y;
if (x != 0 && y != 0)
{
a[x][y] = 1;
index++;
}
}
search(1, index);
int count = 0;
for (int i = 0; i <= index; i++)
{
if (book[i] == 1 && i != 1)
count++;
}
cout << count << endl;
//system("pause");
}