Which of the following functions correctly represent iterative DFS?

Như Quỳnh

New member
Which of the following functions correctly represent iterative DFS?
A.
Code:
void DFS(int s) 
{     
    vector<bool> discovered(V, true); 
    stack<int> st;     
    st.push(s);   
    while (!st.empty()) 
    { 
        s = st.top(); 
        st.pop();         
        if (!discovered[s]) 
        { 
            cout << s << " "; 
            discovered[s] = true; 
        } 
        for (auto i = adjacent[s].begin(); i != adjacent[s].end(); ++i) 
            if (!discovered[*i]) 
                st.push(*i); 
    } 
}
B.
Code:
void DFS(int s) 
{     
    vector<bool> discovered(V, false);     
    stack<int> st;     
    st.push(s);   
    while (!st.empty()) 
    { 
        s = st.top(); 
        st.pop();        
        if (!discovered[s]) 
        { 
            cout << s << " "; 
            discovered[s] = true; 
        } 
        for (auto i = adjacent[s].begin(); i != adjacent[s].end(); ++i) 
            if (!discovered[*i]) 
                st.push(*i); 
    } 
}
C.
Code:
void DFS(int s) 
{     
    vector<bool> discovered(V, false);     
    stack<int> st;     
    st.push(s);   
    while (!st.empty()) 
    { 
        st.pop(); 
        s = st.top();         
        if (!discovered[s]) 
        { 
            cout << s << " "; 
            discovered[s] = true; 
        } 
        for (auto i = adjacent[s].begin(); i != adjacent[s].end(); ++i) 
            if (!discovered[*i]) 
                st.push(*i); 
    } 
}
D.
Code:
void DFS(int s) 
{     
    vector<bool> discovered(V, false);     
    stack<int> st;     
    st.push(s);   
    while (!st.empty()) 
    { 
        s = st.top(); 
        st.pop();         
        if (!discovered[s]) 
        { 
            cout << s << " "; 
            discovered[s] = false; 
        } 
        for (auto i = adjacent[s].begin(); i != adjacent[s].end(); ++i) 
            if (discovered[*i]) 
                st.push(*i); 
    } 
}
 
Answer: B
Explanation: In the correct version we first push the source node into the stack. If the node has not been visited then it is printed and marked as visited. Then the unvisited adjacent nodes are added to the stack. Then the same procedure is repeated for each node of the stack.
 

Tìm kiếm

Back
Top