好友 我想用叉子为5个顶点编写汉密尔顿循环。我想为每个顶点创建一个过程,以检查它是(hamCycleUtil function)的真实顶点还是否。所以我写了这段代码,但是输出错误。我无法解决问题。请帮助。我怎么能写出正确的代码?我只想创建5个进程来检查顶点。
/*
* C Program to Find Hamiltonian Cycle
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include<sys/types.h>
#include<unistd.h>
#define V 5
void printSolution(int path[]);
/*
* check if the vertex v can be added at index 'pos' in the Hamiltonian Cycle
*/
bool isSafe(int v, bool graph[V][V], int path[], int pos)
{
if (graph [path[pos-1]][v] == 0)
return false;
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}
/* solve hamiltonian cycle problem */
bool hamCycleUtil(bool graph[V][V], int path[], int pos)
{
int pid;
int s=-1;//counter
if (pos == V)
{
if (graph[ path[pos-1] ][ path[0] ] == 1)
return true;
else
return false;
}
for (int v = 1; v < V; v++)
{
pid=fork();
s++;
if(s<V)// to control the number of fork
{
if(v==1)
{
pid=1;}
pid=fork();
s++;
if(pid < 0) {
printf("Error");
}
else if (pid == 0){
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
if (hamCycleUtil (graph, path, pos+1) == true)
return true;
path[pos] = -1;
}
}
else {
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
if (hamCycleUtil (graph, path, pos+1) == true)
return true;
path[pos] = -1;
}
}
}
}
return false;
}
/* solves the Hamiltonian Cycle problem using Backtracking.*/
bool hamCycle(bool graph[V][V])
{
int *path = malloc(V*sizeof(int));
for (int i = 0; i < V; i++)
path[i] = -1;
path[0] = 0;
if (hamCycleUtil(graph, path, 1) == false)
{
printf("\nSolution does not exist");
return false;
}
printSolution(path);
return true;
}
/* Main */
void printSolution(int path[])
{
printf("Solution Exists:");
printf(" Following is one Hamiltonian Cycle \n");
for (int i = 0; i < V; i++)
printf(" %d",path[i]);
printf(" %d",path[0]);
}
int main()
{
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
bool graph1[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};
{ hamCycle(graph1);
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) */
bool graph2[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};
hamCycle(graph2);
return 0;
}}