4.LeetCode547 Friend Circles 原题为英文
有个班级,里面有N个学生,他们之中有些是朋友有些不是,比如如果A是B的朋友,B是C的朋友,那么A就是C的间接朋友,我们定义所谓的朋友圈就是由直系和间接朋友所组成的群体。N的范围为 [1,200].
例子 1:
输入:
3
1 1 0
1 1 0
0 0 1
输出: 2
解释:第0个和第1个学生是直系朋友,所以记为1个朋友圈。第2个学生他没什么朋友也要算一个朋友圈,所以结果为2.
例子 2:
输入:
3
1 1 0
1 1 1
0 1 1
输出: 1
可以使用BFS的方法,遍历连通块的个数,就是朋友圈的个数。
代码:
#include <iostream>
#include <queue>
using namespace std;
const int maxn = 205;
int map[maxn][maxn], n; //邻接矩阵
bool inq[maxn] = { false }; //是否进入过队列
void BFS(int u) { //遍历u所在的连通块
queue<int> q; //队列q
q.push(u);
inq[u] = true;
while (!q.empty()) {
int top = q.front();
q.pop();
for (int v = 0; v < n; v++) {
if (map[top][v] == 1 && inq[v] == false) {
q.push(v);
inq[v] = true;
}
}
}
}
int cnt = 0;
void BFSTrave() {
for (int i = 0; i < n; i++) {
if (inq[i] == false) {
BFS(i);
cnt++;
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> map[i][j];
}
}
BFSTrave();
cout << cnt << endl;
return 0;
}