检查是否存在在C ++中连接2个顶点的路径

时间:2018-07-16 09:41:27

标签: c++ graph

我正在尝试编写代码以检查给定图中从顶点v1v2的路径。 适用于某些测试用例,并针对其他测试用例给出运行时错误(超过时间限制)

bool HasPath(int V, int** edges, int* visited, int v1, int v2)
{
    if (edges[v1][v2] == 1)
    {
        return true;
    }

    for (int i = 0; i<V; i++)
    {
        if (visited[i] == 1)
            continue;

        if (edges[v1][i] == 1)
        {
            bool sa = HasPath(V, edges, visited, i, v2);
            visited[i] = 1;
            if (sa == false)
                continue;
            else
                return true;
        }
    }
    return false;
}

int main() {
    int V, E;
    cin >> V >> E;

    int** edges = new int*[V];
    for (int i = 0; i<V; i++)
    {
        edges[i] = new int[V];
        for (int j = 0; j<V; j++)
        {
            edges[i][j] = 0;
        }
    }

    for (int i = 0; i<E; i++)
    {
        int f, s;
        cin >> f >> s;
        edges[f][s] = 1;
        edges[s][f] = 1;
    }

    int* visited = new int[V];
    for (int i = 0; i<V; i++)
        visited[i] = 0;

    int v1, v2;
    cin >> v1 >> v2;
    bool ans = HasPath(V, edges, visited, v1, v2);
    if (ans == 1)
        cout << "true";
    else
        cout << "false";
    return 0;
}

Edges是邻接矩阵。该图是双向的。目的是确定从v1v2的路径是否存在。 输入格式:
第1行:VE
接下来的E行:两个整数ab,表示顶点a和顶点b之间存在边(由空格分隔)
(E+2)行:两个整数v1v2(以空格分隔)

失败的示例测试用例:

6 3
5 3
0 1
3 4
0 3 (these are the vertices between which we need to find path)

上述测试案例的图形:

Here is the image of the graph for the above test case

通过的示例测试用例:

4 4
0 1
0 3
1 2
2 3
1 3

1 个答案:

答案 0 :(得分:1)

我所做的主要更改是在递归函数HasPath中,在递归调用之前将其标记为已访问(visited[i] = 1;)。我还对您的代码进行了一些小的更改。

此外,不要忘记删除动态分配的内存(即使在这里并不重要)。

#include <iostream>
using namespace std;

bool HasPath(int V, int** edges, int* visited, int v1, int v2)
{
    if (edges[v1][v2] == 1)
        return true;

    for (int i = 0; i<V; i++)
    {
        if (visited[i] != 1 && edges[v1][i] == 1)
        {
            visited[i] = 1;
            if (HasPath(V, edges, visited, i, v2))
                return true;
        }
    }
    return false;
}

int main() 
{
    int V, E;
    cin >> V >> E;

    int** edges = new int*[V];
    for (int i = 0; i<V; i++)
    {
        edges[i] = new int[V];
        for (int j = 0; j<V; j++)
        {
            edges[i][j] = 0;
        }
    }

    for (int i = 0; i<E; i++)
    {
        int f, s;
        cin >> f >> s;
        edges[f][s] = 1;
        edges[s][f] = 1;
    }

    int* visited = new int[V];
    for (int i = 0; i<V; i++)
        visited[i] = 0;

    int v1, v2;
    cin >> v1 >> v2;
    bool ans = HasPath(V, edges, visited, v1, v2);
    cout << (ans == 1 ? "true" : "false");

    for (int i = 0; i < V; i++)
        delete[] edges[i];

    delete[] edges;
    delete[] visited;

    return 0;
}