简体   繁体   English

如何在C ++中以网格形状制作无向和无权图

[英]How to make an undirected and unweighted graph in the shape of a grid in C++

I'm trying to implement a for loop to initialize a graph in the shape of a grid, including diagonals. 我正在尝试实现一个for循环,以网格形状(包括对角线)初始化图形。 Basically, I have an array that is initialized with values that I want to replicate in the graph. 基本上,我有一个要初始化的数组,该数组要在图形中复制。 So I have a nested for-loop that has several if statements. 因此,我有一个嵌套的for循环,其中包含多个if语句。 The if statements are used to handle the special cases ie element at index 1,1 only has 3 neighbors. if语句用于处理特殊情况,即索引1,1处的元素只有3个邻居。

I know my graph function works because if I initialize it by hand, it doesn't seg fault and prints the proper BFS, however my loop seg faults. 我知道我的图形函数有效,因为如果我手动对其进行初始化,它不会分段错误并打印正确的BFS,但是我的循环分段错误会出现。 Please take a look: 请看一下:

Graph Class: 图类:

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];

}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
}

void Graph::BFS(int s, int d)
{
    // Mark all the vertices as not visited
    bool *visited = new bool[V];
    int trail[V];
    for(int i = 0; i < V; i++){
        visited[i] = false;
        trail[i] = -1;

    }
  // Create a queue for BFS
  list<int> queue;

// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);

// 'i' will be used to get all adjacent vertices of a vertex
list<int>::iterator i;

while(!queue.empty())
{

    // Dequeue a vertex from queue and print it
    s = queue.front();
    if(s == d){

        break;
    }
    else

    queue.pop_front();

    // Get all adjacent vertices of the dequeued vertex s
    // If a adjacent has not been visited, then mark it visited
    // and enqueue it
    for(i = adj[s].begin(); i != adj[s].end(); ++i)
    {
        if(!visited[*i])
        {
            visited[*i] = true;
            queue.push_back(*i);
            trail[*i] = s;
        }

    }

 }
int x = d;
while(x != -1){

   cout<<x<<endl;
   x = trail[x];


   }  
}

In main program: 在主程序中:

int num = 2;

int arr[num+1][num+1];
int x = 1;
for(int i = 1; i<=num; i++){
    for(int j = 1; j<= num; j++){

        arr[i][j] = x;


        cout<<x<<" ";
        x++;

    }
    cout<<endl;

}

int max = 2;
Graph g(max+1);

for(int row = 1; row <= max; row++){

    for(int col = 1; col <= max; col++){

        if(row == 1 && col == 1){

            g.addEdge(arr[row][col],(arr[row][col] +1));
            g.addEdge(arr[row][col],(arr[row][col] +max));
            g.addEdge(arr[row][col],(arr[row][col] + max+1));

        }
        else if(row ==1 && col == max){
            g.addEdge(arr[row][col],(arr[row][col]-1));
            g.addEdge(arr[row][col],(arr[row][col]+max));
            g.addEdge(arr[row][col],(arr[row][col]+max-1));


        }

        else if(row == max && col == max){
            g.addEdge(arr[row][col],(arr[row][col]-1));
            g.addEdge(arr[row][col],(arr[row][col]-max));
            g.addEdge(arr[row][col],(arr[row][col]-max-1));

        }
        else if(row == max && col == 1){
            g.addEdge(arr[row][col],(arr[row][col]-max));
            g.addEdge(arr[row][col],(arr[row][col]-max+1));
            g.addEdge(arr[row][col],(arr[row][col]+1));

        }
        else if(row == max){
            g.addEdge(arr[row][col],(arr[row][col]-1));
            g.addEdge(arr[row][col],(arr[row][col]+1));
            g.addEdge(arr[row][col],(arr[row][col]-max));
            g.addEdge(arr[row][col],(arr[row][col]-max-1));
            g.addEdge(arr[row][col],(arr[row][col]-max+1));

        }
        else if(col == max){

            g.addEdge(arr[row][col],(arr[row][col]-1));
            g.addEdge(arr[row][col],(arr[row][col]-max));
            g.addEdge(arr[row][col],(arr[row][col]+max));
            g.addEdge(arr[row][col],(arr[row][col]-max-1));
            g.addEdge(arr[row][col],(arr[row][col]+max-1));

        }
        else if(col == 1){
           g.addEdge(arr[row][col],(arr[row][col]+1));
           g.addEdge(arr[row][col],(arr[row][col]+max));
           g.addEdge(arr[row][col],(arr[row][col]-max));
           g.addEdge(arr[row][col],(arr[row][col]-max+1));
           g.addEdge(arr[row][col],(arr[row][col]+max+1));

        }
        else if(row == 1){
            g.addEdge(arr[row][col],(arr[row][col]-1));
            g.addEdge(arr[row][col],(arr[row][col]+1));
            g.addEdge(arr[row][col],(arr[row][col]+max));
            g.addEdge(arr[row][col],(arr[row][col]+max-1));
            g.addEdge(arr[row][col],(arr[row][col]+max+1));

        }
        else{

            g.addEdge(arr[row][col],(arr[row][col]+1));
            g.addEdge(arr[row][col],(arr[row][col]-1));
            g.addEdge(arr[row][col],(arr[row][col]+max));
            g.addEdge(arr[row][col],(arr[row][col]-max));
            g.addEdge(arr[row][col],(arr[row][col]-max-1));
            g.addEdge(arr[row][col],(arr[row][col]-max+1));
            g.addEdge(arr[row][col],(arr[row][col]+max-1));
            g.addEdge(arr[row][col],(arr[row][col]+max+1));
        }
    }
}

Note: I wanted my graph vertices to start at 1 but not at 0. This is why my matrix has an extra row and column in it. 注意:我希望图形顶点从1开始但不从0开始。这就是为什么矩阵中有额外的行和列的原因。 Also, my graph requires an edge to be added in both directions, so it would be 1--->0 and 0--->1. 另外,我的图要求在两个方向上都添加一条边,因此它将是1 ---> 0和0 ---> 1。

It appears that your constructor only allocates N adjacency lists, but you then define N × N nodes. 看来您的构造函数仅分配N个邻接列表,但是您随后定义了N × N个节点。 You call addEdge() with each of these nodes as its first argument, which when you get to node N +1, tries to write past the end of adj and causes a buffer overflow. 调用addEdge()并将这些节点中的每个节点作为第一个参数,当到达节点N +1时,它将尝试写到adj的末尾并导致缓冲区溢出。

To catch this kind of bug in the future, you can define adj as a std::vector , which comes with bounds checking. 要在将来捕获这种错误,可以将adj定义为std::vector ,它带有边界检查。 This will do all the work of making it possible to add nodes for you, and also fix the memory leak caused by the absence of a destructor that deletes arr . 这将完成所有可能的工作,为您添加节点,并修复由于缺少删除arr的析构函数而导致的内存泄漏。 If for some reason you can't use std::vector or std::array , my advice would be to at least manually bounds-check with a line such as assert(v < V); 如果由于某种原因您不能使用std::vectorstd::array ,我的建议是至少使用诸如assert(v < V);这样的行手动进行边界检查assert(v < V); in Graph::addEdge() . Graph::addEdge()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM