📜  哈密顿路径(使用动态规划)

📅  最后修改于: 2021-09-17 07:24:33             🧑  作者: Mango

给定一个由N个顶点组成的无向图的邻接矩阵adj[][] ,任务是找出该图是否包含哈密顿路径。如果发现是真的,则打印“是” 。否则,打印“否”

例子:

朴素方法:解决给定问题的最简单方法是生成N个顶点的所有可能排列。对于每个排列,通过检查相邻顶点之间是否存在边来检查它是否是有效的哈密顿路径。如果发现是真的,则打印“是” 。否则,打印“否”

时间复杂度: O(N * N!)
辅助空间: O(1)

高效方法:上述方法可以通过使用基于以下观察的动态编程和位掩码来优化:

  • 我们的想法是这样的,每子集的顶点为S,检查是否有子集中的哈密尔顿路径s的顶点v,其中v€s表示结束。
  • 如果v有一个邻居u ,其中u € S – {v} ,因此,存在一条终止于顶点u的哈密顿路径。
  • 该问题可以通过推广哈密顿路径的顶点子集和结束顶点来解决。

请按照以下步骤解决问题:

  • 初始化一个布尔矩阵DP [] []的尺寸N * 2 N,其中DP [j]的[i]表示是否存在在子集中是否存在路径或未被掩模I表示的是每一个顶点的访问在曾经和端部在顶点j
  • 对于基本情况,更新dp[i][1 << i] = true ,因为i[0, N – 1]范围内
  • 使用变量i迭代范围[1, 2 N – 1]并执行以下步骤:
    • 在掩码i 中设置了位的所有顶点都包含在子集中。
    • 使用变量j在范围[1, N] 上迭代该变量将表示当前子集掩码i的汉密尔顿路径的结束顶点,并执行以下步骤:
      • 如果i2 j 的值为真,则使用变量k在范围[1, N] 上迭代,如果dp[k][i^2 j ] 的值为,则标记dp[j][ i]并跳出循环。
      • 否则,继续下一次迭代。
  • 使用变量i迭代范围,如果dp[i][2 N – 1] 的值为true ,则存在以顶点i结束的哈密顿路径。因此,打印“是” 。否则,打印“否”

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
const int N = 5;
 
// Function to check whether there
// exists a Hamiltonian Path or not
bool Hamiltonian_path(
    vector >& adj, int N)
{
    int dp[N][(1 << N)];
 
    // Initialize the table
    memset(dp, 0, sizeof dp);
 
    // Set all dp[i][(1 << i)] to
    // true
    for (int i = 0; i < N; i++)
        dp[i][(1 << i)] = true;
 
    // Iterate over each subset
    // of nodes
    for (int i = 0; i < (1 << N); i++) {
 
        for (int j = 0; j < N; j++) {
 
            // If the jth nodes is included
            // in the current subset
            if (i & (1 << j)) {
 
                // Find K, neighbour of j
                // also present in the
                // current subset
                for (int k = 0; k < N; k++) {
 
                    if (i & (1 << k)
                        && adj[k][j]
                        && j != k
                        && dp[k][i ^ (1 << j)]) {
 
                        // Update dp[j][i]
                        // to true
                        dp[j][i] = true;
                        break;
                    }
                }
            }
        }
    }
 
    // Traverse the vertices
    for (int i = 0; i < N; i++) {
 
        // Hamiltonian Path exists
        if (dp[i][(1 << N) - 1])
            return true;
    }
 
    // Otherwise, return false
    return false;
}
 
// Driver Code
int main()
{
 
    // Input
    vector > adj = { { 0, 1, 1, 1, 0 },
                                 { 1, 0, 1, 0, 1 },
                                 { 1, 1, 0, 1, 1 },
                                 { 1, 0, 1, 0, 0 } };
    int N = adj.size();
 
    // Function Call
    if (Hamiltonian_path(adj, N))
        cout << "YES";
    else
        cout << "NO";
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to check whether there
// exists a Hamiltonian Path or not
static boolean Hamiltonian_path(int adj[][], int N)
{
    boolean dp[][] = new boolean[N][(1 << N)];
 
    // Set all dp[i][(1 << i)] to
    // true
    for(int i = 0; i < N; i++)
        dp[i][(1 << i)] = true;
 
    // Iterate over each subset
    // of nodes
    for(int i = 0; i < (1 << N); i++)
    {
        for(int j = 0; j < N; j++)
        {
             
            // If the jth nodes is included
            // in the current subset
            if ((i & (1 << j)) != 0)
            {
 
                // Find K, neighbour of j
                // also present in the
                // current subset
                for(int k = 0; k < N; k++)
                {
                     
                    if ((i & (1 << k)) != 0 &&
                         adj[k][j] == 1 && j != k &&
                           dp[k][i ^ (1 << j)])
                    {
                         
                        // Update dp[j][i]
                        // to true
                        dp[j][i] = true;
                        break;
                    }
                }
            }
        }
    }
 
    // Traverse the vertices
    for(int i = 0; i < N; i++)
    {
         
        // Hamiltonian Path exists
        if (dp[i][(1 << N) - 1])
            return true;
    }
 
    // Otherwise, return false
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    int adj[][] = { { 0, 1, 1, 1, 0 },
                    { 1, 0, 1, 0, 1 },
                    { 1, 1, 0, 1, 1 },
                    { 1, 0, 1, 0, 0 } };
    int N = adj.length;
 
    // Function Call
    if (Hamiltonian_path(adj, N))
        System.out.println("YES");
    else
        System.out.println("NO");
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for the above approach
 
# Function to check whether there
# exists a Hamiltonian Path or not
def Hamiltonian_path(adj, N):
     
    dp = [[False for i in range(1 << N)]
                 for j in range(N)]
 
    # Set all dp[i][(1 << i)] to
    # true
    for i in range(N):
        dp[i][1 << i] = True
 
    # Iterate over each subset
    # of nodes
    for i in range(1 << N):
        for j in range(N):
 
            # If the jth nodes is included
            # in the current subset
            if ((i & (1 << j)) != 0):
 
                # Find K, neighbour of j
                # also present in the
                # current subset
                for k in range(N):
                    if ((i & (1 << k)) != 0 and
                             adj[k][j] == 1 and
                                     j != k and
                          dp[k][i ^ (1 << j)]):
                         
                        # Update dp[j][i]
                        # to true
                        dp[j][i] = True
                        break
     
    # Traverse the vertices
    for i in range(N):
 
        # Hamiltonian Path exists
        if (dp[i][(1 << N) - 1]):
            return True
 
    # Otherwise, return false
    return False
 
# Driver Code
adj = [ [ 0, 1, 1, 1, 0 ] ,
        [ 1, 0, 1, 0, 1 ],
        [ 1, 1, 0, 1, 1 ],
        [ 1, 0, 1, 0, 0 ] ]
 
N = len(adj)
 
if (Hamiltonian_path(adj, N)):
    print("YES")
else:
    print("NO")
 
# This code is contributed by maheshwaripiyush9


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to check whether there
// exists a Hamiltonian Path or not
static bool Hamiltonian_path(int[,] adj, int N)
{
    bool[,] dp = new bool[N, (1 << N)];
 
    // Set all dp[i][(1 << i)] to
    // true
    for(int i = 0; i < N; i++)
        dp[i, (1 << i)] = true;
 
    // Iterate over each subset
    // of nodes
    for(int i = 0; i < (1 << N); i++)
    {
        for(int j = 0; j < N; j++)
        {
             
            // If the jth nodes is included
            // in the current subset
            if ((i & (1 << j)) != 0)
            {
                 
                // Find K, neighbour of j
                // also present in the
                // current subset
                for(int k = 0; k < N; k++)
                {
                     
                    if ((i & (1 << k)) != 0 &&
                        adj[k, j] == 1 && j != k &&
                        dp[k, i ^ (1 << j)])
                    {
 
                        // Update dp[j][i]
                        // to true
                        dp[j, i] = true;
                        break;
                    }
                }
            }
        }
    }
 
    // Traverse the vertices
    for(int i = 0; i < N; i++)
    {
         
        // Hamiltonian Path exists
        if (dp[i, (1 << N) - 1])
            return true;
    }
 
    // Otherwise, return false
    return false;
}
 
// Driver Code
public static void Main(String[] args)
{
    int[,] adj = { { 0, 1, 1, 1, 0 },
                   { 1, 0, 1, 0, 1 },
                   { 1, 1, 0, 1, 1 },
                   { 1, 0, 1, 0, 0 } };
    int N = adj.GetLength(0);
 
    // Function Call
    if (Hamiltonian_path(adj, N))
        Console.WriteLine("YES");
    else
        Console.WriteLine("NO");
}
}
 
// This code is contributed by ukasp


Javascript


输出:
YES

时间复杂度: O(N * 2 N )
辅助空间: O(N * 2 N )

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程