What I did not know about BFS

Правка en6, от nobody_6e72, 2026-08-22 10:16:29

So compare the following codes and here is the question, SPOT THE REASON FOR THE DIFFERENCE IN TIME COMPLEXITIES in these 2 codes --

vector<vector<int>> adj_list;
queue<int> q;
vector[int] visited(n, 0);

q.push({source});
while (! q.empty()){
    int next = q.front();
    q.pop();
    visited[next] = 1; // <----
    for (int neigh: adj_list[next]){
        if (visited[neigh] != 1){
            q.add(neigh);
        }
    }
}

vector<vector<int>> adj_list;
queue<int> q;
vector[int] visited(n, 0);

q.push({source});
visited[source] = 1; // <----
while (! q.empty()){
    int next = q.front();
    q.pop();
    for (int neigh: adj_list[next]){
        if (visited[neigh] != 1){
            q.add(neigh);
            visited[neigh] = 1; // <----
        }
    }
}

Reason: Consider the example {{1, 2}, {1, 3}, {2, 3}} and {a, b} represents directed edge from a to b then 1 gets explored and 2 and 3 get added but neither one get marked as visitde in code-1 and so if 2 is explored next then 3 will again get added into the queue as 3 was never marked visited. And hence the time complexity goes from linear which is the one that people learn in school to Fibonacci form (I mean the recurrence transforms to represent a Fibonacci Sequence).

I am sharing this because it is something I never chose to question earlier and thanks to random solving and LC200 for helping this misconception of mine come to surface. I would appreciate any kind of improvement or efficiency on top of what I have done.

_Also as something to begin discussions in the comment section, could you share what you find to be the most exciting application of BFS as part of another problem or as part of your work (employment or research) etc. These little things give me a very good feeling inside when they are actually applied to solve something important.

Теги misconception, graphs, bfs

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en8 Английский nobody_6e72 2026-08-22 10:17:37 0 (published)
en7 Английский nobody_6e72 2026-08-22 10:17:16 18
en6 Английский nobody_6e72 2026-08-22 10:16:29 2 Tiny change: 'done.\n\n_Also as s' -> 'done.\n\n_\_Also as s'
en5 Английский nobody_6e72 2026-08-22 10:16:10 10
en4 Английский nobody_6e72 2026-08-22 10:15:42 415
en3 Английский nobody_6e72 2026-08-22 10:13:06 35
en2 Английский nobody_6e72 2026-08-22 10:12:16 1387
en1 Английский nobody_6e72 2026-08-21 16:40:34 522 Initial revision (saved to drafts)