Graph Theory(Breadth First Search)
Hellllo, guys new article again WOwwwww in this article I will talk about another search way in
graph topic, which is DFS.
ok, as you see now in this image Bfs is working by search level by level it searches in the level one
first then when it's complete level one it starts a search in the next level and so on.
(notes that Bfs work in an unweighted graph or weighted graph with equal-weighted)
(notes that Bfs is used to search to the shortest path) EXAMPLE:(maze solver)
now, we wanna ask a question how can i know the level of the node in implementation?
we will write this algorithm by using a queue of pair the first one will be the value of the node and the second one will be the level .
Like:
vector<int> BFS(int s, vector<vector<int> > & adjList) {
vector<int> len(sz(adjList), OO); //oo is define to infinity
queue< pair<int, int> > q;
q.push(MP(s, 0)), len[s] = 0;
int cur, dep;
while(!q.empty()) {
pair<int, int> p = q.front(); q.pop();
cur = p.first, dep = p.second;
rep(i, adjList[cur]) if (len[adjList[cur][i]] == OO)
q.push(MP(adjList[cur][i], dep+1)), len[adjList[cur][i]] = dep+1;
}
return len; //cur is the furthest node from s with depth dep
}
ok we can implement this code by another way which is process the graph level by level
Like:
vector<int> BFS2(int s, vector<vector<int> > & adjList) {
vector<int> len(sz(adjList), OO);
queue<int> q;
q.push(s), len[s] = 0;
int dep = 0, cur = s, sz = 1;
for (; !q.empty(); ++dep, sz = q.size()) {
while (sz--) {
cur = q.front(), q.pop();
rep(i, adjList[cur]) if (len[adjList[cur][i]] == OO)
q.push(adjList[cur][i]), len[adjList[cur][i]] = dep+1;
}
}
return len; //cur is the furthest node from s with depth dep
}
Comments
Post a Comment