C++에서 깊이 우선 검색 알고리즘을 구현하려고 할 때 읽기 액세스 위반 (read access violation when I tried to implement Depth First Search algorithm in c++)


문제 설명

C++에서 깊이 우선 검색 알고리즘을 구현하려고 할 때 읽기 액세스 위반 (read access violation when I tried to implement Depth First Search algorithm in c++)

이것은 내 DFS 기능입니다. 내가 메인 함수에서 방문 배열을 할당했는데도 방문[start_vertex]이 작동하지 않는 이유를 모르겠다!

6
                    typedef Node** PtP;
                    void DFS(PtP list, int start_vertex, bool* visited)
                    {
                        cout << "the crash under this line";
                        if (visited[start_vertex])
                        {
                            cout << "ignore";
                        }
                        visited[start_vertex] = true;
                        Node* adj = list[start_vertex];  // linked list list[0]
                        //  after this line start_vertex will be adjacency vertex of start vertex
                        while (adj != NULL)
                        {


                            DFS(list, adj‑>data, visited);
                            adj = adj‑>next;

                        }
                    }

이것은 내가 bool 배열을 생성하고 그것을 4개의 요소로 할당한 나의 메인 함수이다. DFS 기능을 연결합니다.

int main()
{
    PtP list;
    list = new Node * [4];
    for (int i = 0; i < 4; i++)
    {
        list[i] = new Node[4];
        list[i] = NULL;
    }

    for (int i = 0; i < 4; i++)
    {
        cout << "enter number of vertices adjacency with " << i << ": ";
        int temp;
        cin >> temp;
        addEdge2(list, i, temp);
    }

    for (int i = 0; i < 4; i++)
    {
        cout << "list[" << i << "]: ";
        traverse(list[i]);
    }
    bool* visited = new bool[4];
    for (int i = 0; i < 4; i++)
    {
        visited = false;
    }
    DFS(list, 0, visited);
    for (int i = 0; i < 4; i++)
    {
        cout << "visisted: " << visited[i] << " ";
    }
    for (int i = 0; i < 4; i++)
    {
        delete [] list[i];
    }
    delete [] list;
    return 0;

}

DFS 방법 테스트를 위한 전체 프로그램입니다.

#include <iostream>

using namespace std;
class Node {
public: 
    int data;
    Node* next;

};
typedef Node* Ptr;
typedef Node** PtP;

void addFront(Ptr& First, int x)
{
    Ptr p;
    p = new Node;
    p‑>data = x;
    p‑>next = First;
    First = p;
}
void addEdge(PtP &list, int v1, int v2)
{
    addFront(list[v1], v2);
    addFront(list[v2], v1);

}

void addEdge2(PtP& list, int v, int num_of_adj_vtex)
{
    cout << "enter vertices adjacency with  " << v << ": ";
    int temp;
    for (int i = 0; i < num_of_adj_vtex; i++)
    {
        cin >> temp;
        addFront(list[v], temp);
    }
}
void traverse(Node* first)
{
    Node* p = first;
    while (p != NULL)
    {
        cout << p‑>data<<" ";
        p = p‑>next;
    }
    cout << "\n";
}


void DFS(PtP list, int start_vertex, bool* visited)
{

    if (visited[start_vertex])
    {

        cout << "vertex: " << start_vertex << " visited ";
    }
    visited[start_vertex] = true;
     // linked list list[0] after this line start_vertex will be adjaceny vertex of start vertex
    Node* adj = list[start_vertex];
    while (adj != NULL)
    {


        DFS(list, adj‑>data, visited);
        adj = adj‑>next;

    }
}
int main()
{
    PtP list; //type def node ** ptp
    list = new Node * [4];
    for (int i = 0; i < 4; i++)
    {
        list[i] = NULL;
    }

    for (int i = 0; i < 4; i++)
    {
        cout << "enter number of vertices adjacency with " << i << ": ";
        int temp;
        cin >> temp;
        addEdge2(list, i, temp);
    }

    for (int i = 0; i < 4; i++)
    {
        cout << "list[" << i << "]: ";
        traverse(list[i]);
    }
    bool* visited = new bool[4];
    for (int i = 0; i < 4; i++)
    {
        visited[i] = false;
    }
    DFS(list, 0, visited);
    for (int i = 0; i < 4; i++)
    {
        cout << "visisted: " << i << " "<< visited[i] << " ";
    }




    delete [] list;
    return 0;

}

참조 솔루션

방법 1:

Ok, from what I can see, the problem seems to be user input related. The method:

void addEdge2(PtP& list, int v, int num_of_adj_vtex)
{
    cout << "enter vertices adjacency with  " << v << ": ";
    int temp;
    for (int i = 0; i < num_of_adj_vtex; i++)
    {
        cin >> temp;
        addFront(list[v], temp); //Here if temp > 3 your later code will fail.
    }
}

Requests user input and stores it at the front of the list...whatever is the value of temp, and puts it into the data field.

Later on when you do the DFS method you call the same method recursively:

        DFS(list, adj‑>data, visited);
        adj = adj‑>next;

This depends on what adj‑>data has stored, from the addEdge2 function. Since you have set the boolean array to a length of 4, that adj‑>data must be pointing to any value > 3 which would throw the error you mentioned because it is trying to access unallocated memory.

It seems like the code is not wrong, exactly, even though you could probably set some safeguards like making sure the user enters a value from 0 to 3.

(by Phạm Hoàng ViệtMiltoxBeyond)

참조 문서

  1. read access violation when I tried to implement Depth First Search algorithm in c++ (CC BY‑SA 2.5/3.0/4.0)

#depth-first-search #C++






관련 질문

깊이 우선 탐색 트리 에지 분류 (Depth first search tree edge classification)

무방향 그래프에서 노드에 대한 최단 경로 찾기 (Finding the shortest path to a node in an undirected graph)

깊이 우선 탐색 가능한 노드 (Depth First Search Possible Nodes)

깊이 우선 검색을 사용하여 트리에서 노드 찾기 (Finding a node in a tree using Depth First Search)

행렬에서 섬을 찾기 위해 DFS 구현 문제 (Problem implementing DFS to find islands in a matrix)

Python에서 재귀 DFS를 효율적으로 구현하는 방법은 무엇입니까? (How to implement recursive DFS in Python efficiently?)

bfs/dfs의 모든 노드를 방문하는 경로를 추적하는 방법 (How to trace the path that visits all nodes in bfs/dfs)

그래프에서 주기를 감지하기 위한 시간 복잡도 (Time complexity for detecting a cycle in a graph)

트리에서 두 노드 사이의 경로를 찾는 방법은 무엇입니까? (How to find the path between 2 nodes in a tree?)

BFS 순회는 완전한 무방향 그래프에서 DFS와 동일합니까? (Is BFS traversal the same as DFS in a Complete Undirected Graph?)

C++에서 깊이 우선 검색 알고리즘을 구현하려고 할 때 읽기 액세스 위반 (read access violation when I tried to implement Depth First Search algorithm in c++)

코스 일정 - 토폴로지 정렬 (Course schedule - Topological sort)







코멘트