给定N个顶点的无向完整图,其中N>2。任务是找到图的不同哈密顿圈数。
完整图:如果每个可能的顶点通过边连接,则认为图是完整的。
汉密尔顿周期:这是一个封闭的步行过程,每个顶点除初始顶点外最多被访问一次。并不需要走遍所有的边缘。
公式:
例子:
Input : N = 6
Output : Hamiltonian cycles = 60
Input : N = 4
Output : Hamiltonian cycles = 3
解释:
让我们以N = 4个完全无向图为例,这3个不同的哈密顿循环如下所示:
下面是上述方法的实现:
C++
// C++ program for implementation of the
// above program
#include
using namespace std;
// Function that calculates
// number of Hamiltonian cycle
int Cycles(int N)
{
int fact = 1, result = 0;
result = N - 1;
// Calculating factorial
int i = result;
while (i > 0) {
fact = fact * i;
i--;
}
return fact / 2;
}
// Driver code
int main()
{
int N = 5;
int Number = Cycles(N);
cout << "Hamiltonian cycles = " << Number;
return 0;
}
Java
// Java program for implementation
// of the above program
class GFG
{
// Function that calculates
// number of Hamiltonian cycle
static int Cycles(int N)
{
int fact = 1, result = 0;
result = N - 1;
// Calculating factorial
int i = result;
while (i > 0)
{
fact = fact * i;
i--;
}
return fact / 2;
}
// Driver code
public static void main(String[] args)
{
int N = 5;
int Number = Cycles(N);
System.out.println("Hamiltonian cycles = " +
Number);
}
}
// This code is contributed
// by Code_Mech.
Python3
# Python3 program for implementation
# of the above program
import math as mt
# Function that calculates
# number of Hamiltonian cycle
def Cycles(N):
fact = 1
result = N - 1
# Calculating factorial
i = result
while (i > 0):
fact = fact * i
i -= 1
return fact // 2
# Driver code
N = 5
Number = Cycles(N)
print("Hamiltonian cycles = ",
Number)
# This code is contributed
# by Mohit Kumar
C#
// C# program for implementation of
// the above program
using System;
class GFG
{
// Function that calculates
// number of Hamiltonian cycle
static int Cycles(int N)
{
int fact = 1, result = 0;
result = N - 1;
// Calculating factorial
int i = result;
while (i > 0)
{
fact = fact * i;
i--;
}
return fact / 2;
}
// Driver code
public static void Main()
{
int N = 5;
int Number = Cycles(N);
Console.Write("Hamiltonian cycles = " +
Number);
}
}
// This code is contributed
// by Akanksha Rai
PHP
0)
{
$fact = $fact * $i;
$i--;
}
return floor($fact / 2);
}
// Driver code
$N = 5;
$Number = Cycles($N);
echo "Hamiltonian cycles = ",
$Number;
// This code is contributed by Ryuga
?>
Javascript
输出:
Hamiltonian cycles = 12