Using BFS algorithm to find the shortest path

后端 未结 4 1283
礼貌的吻别
礼貌的吻别 2021-01-07 03:58
std::list  q;
std::vector visited(cols + 1);
for(int i = 1; i <= cols; i++) visited[i] = false;
visited[x] = true;
if(!l[x].empty())
{
             


        
4条回答
  •  醉梦人生
    2021-01-07 04:31

    No,you don't have to change much in your code. just replace replace stack in case of DFS with Queue and it will become BFS.

    Difference in implementation of BFS and DFS is that "BFS is implemented using Queue and DFS is using Stack" (Reason is obvious that DFS does depth like in maze.)

    SEE changes for yourself:

    DFS:

    void dfs(int start)
    {
        int j,temp; 
        stack s; //STACK
        s.push(start);
        vector:: iterator it;
        while(s.empty()==0)
        {
            temp=s.top(); // Top element from Stack
            s.pop();
            status[temp]=1; // marked as visited , 0 means unvisited
            cout<

    BFS:

    void bfs(int start)
    {
        int j,temp; 
        queue q; // QUEUE
        q.push(start);
        vector:: iterator it;
        while(q.empty()==0)
        {
            temp=q.front(); // Front element from Queue
            q.pop();
            status[temp]=1; // marked as visited , 0 means unvisited
            cout<

    As you can see implementation of both just differ "in use of STACK and QUEUE".

    Hope this helps !

提交回复
热议问题