有向圖的帶深度bfs搜索,用dfs有一些問題要處理,比如一個點離起始點很近,
但它可能會被其他離起始點很近的點dfs搜索路徑上,這時要保證能從這個點dfs一趟,因爲這個點下面可能還有點滿足題目的條件。
代碼如下:
#include <iostream>
#include <cstdio>
#include <fstream>
#include <vector>
using namespace std;
//ifstream in("1076.txt"); //從文件讀取輸入
//#define cin in
bool visited[1001] = {false};
int map[1001][1001];
int max1;
int N;
void bfs(int begin,int L)
{
visited[begin] = true;
vector<int> tmp;
for(int i = 1;i<=N;i++)
if(L > 0 && visited[i] == false && map[begin][i] == 1)
{
max1++;
visited[i] = true;
tmp.push_back(i);
}
for(int j = 0;j<tmp.size();j++)
{
bfs(tmp[j],L-1);
}
return;
}
int main()
{
int L;
cin >> N >> L;
int i;
for(i = 1;i<=N;i++)
{
int m;
cin >> m;
while(m--)
{
int temp;
cin >> temp;
map[temp][i] = 1;
}
}
int k;
cin >> k;
while(k--)
{
int user;
cin >> user;
max1 = 0;
for(i = 1;i<=N;i++)
{
visited[i] = false;
}
bfs(user,L);
cout << max1 << endl;
}
return 0;
}