广度优先遍历
模板题,注意一下无向边,根据数据范围开两倍边集。直接上模板。
const int N = 200010,M = 400010;
class Solution {
public:
int h[N],e[M],ne[M],idx;
void add(int a,int b){
e[idx] = b,ne[idx] = h[a] , h[a] = idx++;
}
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
idx = 0;
memset(h,-1,sizeof h);
for(auto &&e:edges)
add(e[0],e[1]), add(e[1],e[0]);
queue<int> qu;
qu.push(source);
bool st[n];
memset(st,0,sizeof st);
st[source] = true;
while(qu.size()){
int a = qu.front();
qu.pop();
if(a==destination) break;
for(int i = h[a];i!=-1;i = ne[i]){
int j = e[i];
if(!st[j]){
st[j] = true;
qu.push(j);
}
}
}
return st[destination];
}
};
- 时间复杂度 : O ( M ) O(M) O(M) , M M M 是边的数量, b f s bfs bfs 至多遍历所有边一次,时间复杂度 O ( M ) O(M) O(M) 。
- 空间复杂度 : O ( N + M ) O(N+M) O(N+M) , N N N 是点的数量,点集和边集的空间复杂度 O ( N + M ) O(N+M) O(N+M) 。
AC
致语
- 经典题,直接用模板
- 读者有问题请留言,墨染看到就会回复的。