Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
This is my Code C++ for my assignment. Please help me to convert it to C code. Thank you!

What I have tried:

#include<stdio.h>
#define NODE 4


int graph[NODE][NODE];
int path[NODE];

void displayCycle() {    //Function to display the cycle obtained
   printf("The Hamilton Cycle : \n");

   for (int i = 0; i < NODE; i++)
      printf(path[i] + "  ");
   cout << path[0] << endl;      //print the first vertex again
}

bool isValid(int v, int k) {
   if (graph [path[k-1]][v] == 0)   //if there is no edge
      return false;

   for (int i = 0; i < k; i++)   //if vertex is already taken, skip that
      if (path[i] == v)
         return false;
   return true;
}

bool cycleFound(int k) {
   if (k == NODE) {             //when all vertices are in the path
      if (graph[path[k-1]][ path[0] ] == 1 )
         return true;
      else
         return false;
   }

   for (int v = 1; v < NODE; v++) {       //for all vertices except starting point
      if (isValid(v,k)) {                //if possible to add v in the path
         path[k] = v;
         if (cycleFound (k+1) == true)
            return true;
         path[k] = -1;               //when k vertex will not in the solution
      }
   }
   return false;
}

bool hamiltonianCycle() {
   for (int i = 0; i < NODE; i++)
      path[i] = -1;
   path[0] = 0;     //first vertex as 0

   if ( cycleFound(1) == false ) {
      cout << "Solution does not exist"<<endl;
      return false;
   }

   displayCycle();
   return true;
}

int main() {
	int i,j;
	cout << "Enter the Graph : " << endl;
	for (i=0;i<NODE;i++){
		for (j=0;j<NODE;j++){
			cout << "Graph G(" << (i+1) << "," << (j+1) << ") = ";
			cin >> graph[i][j];
		}
	}
	cout << endl;
	cout << "The Graph :" << endl;
	for (i=0;i<NODE;i++){
		for (j=0;j<NODE;j++){
			cout << graph [i][j] << "\t";
		}
		cout << endl;
	}
	
	cout << endl;
	
   	hamiltonianCycle();
  }
Posted
Updated 15-Jan-23 20:06pm
v3
Comments
Dave Kreskowiak 25-Apr-21 11:42am    
You can try to turn this converted code in as your own work, but don't expect a passing grade.

1 solution

The C equivalent of iostream is stdio.h. It looks like most of the work involves rewriting the lines that use cin and cout to use stdio.h. See here[^] and here[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900