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

📅  最后修改于: 2021-04-17 17:40:35             🧑  作者: Mango

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

例子:

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

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

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

  • 这个想法是这样的,顶点的每一个子集S检查是否存在的子集的哈密尔顿路径s的顶点v,其中v€s表示结束。
  • 如果v具有邻居u ,其中u€– {v} ,那么存在一条以顶点u结束的哈密顿路径。
  • 该问题可以通过概括汉密尔顿路径的顶点子集和结束顶点来解决。

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

  • 初始化一个布尔矩阵DP [] [尺寸N * 2 N,其中DP [j]的[i]表示是否存在在子集中是否存在路径或未被掩模I表示的]为每一个顶点的访问在曾经和端部在顶点j处
  • 对于基本情况下,更新DP [I] [1 << i]于范围=真,对于i [0,N – 1]
  • 使用变量i遍历[1,2 N – 1]范围并执行以下步骤:
    • 所有在掩码i中设置了位的顶点都包含在子集中。
    • 使用变量j在范围[1,N]上进行迭代该变量将表示当前子集蒙版i的哈密顿路径的末端顶点,并执行以下步骤:
      • 如果i2 j的值为true,则使用变量k在范围[1,N]上进行迭代;如果dp [k] [i ^ 2 j ]的值为true ,则标记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


输出:
YES

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