DAA Lab
DAA Lab
Develop a program and measure the running time for identifying solution
for n-Queens problem with Backtracking.
// C program to solve N Queen Problem using backtracking
#include <stdbool.h>
#include <stdio.h>
#define N 4
// A utility function to print solution
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if(board[i][j])
printf("Q ");
else
printf(". ");
}
printf("\n");
}
}
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
// Driver program to test above function
int main()
{
solveNQ();
return 0;
}
Output
..Q.
Q...
...Q
.Q..
9. Develop a program and measure the running time for Graph Colouring
with Backtracking
// C program for solution of M Colouring problem using backtracking
#include <stdbool.h>
#include <stdio.h>
// Number of vertices in the graph
#define V 4
void printSolution(int color[]);
bool isSafe(int v, bool graph[V][V], int color[], int c)
{
for (int i = 0; i < V; i++)
if (graph[v][i] && c == color[i])
return false;
return true;
}
// Driver code
int main()
{
bool graph[V][V] = {
{ 0, 1, 1, 1 },
{ 1, 0, 1, 0 },
{ 1, 1, 0, 1 },
{ 1, 0, 1, 0 },
};
int m = 3; // Number of colors
// Function call
graphColoring(graph, m);
return 0;
}
Output
Solution Exists: Following are the assigned colors
1 2 3 2
return 1;
}
/* A recursive utility function to solve hamiltonian cycle problem */
int hamCycleUtil(int graph[V][V], int path[], int pos)
{
/* base case: If all vertices are included in Hamiltonian Cycle */
if (pos == V)
{
// And if there is an edge from the last included vertex to the
// first vertex
if ( graph[ path[pos-1] ][ path[0] ] == 1 )
return 1;
else
return 0;
}
// Try different vertices as a next candidate in Hamiltonian Cycle.
// We don't try for 0 as we included 0 as starting point in hamCycle()
for (int v = 1; v < V; v++)
{
/* Check if this vertex can be added to Hamiltonian Cycle */
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
11. Develop a program and measure the running time running time to
generate solution of Knapsack problem with Backtracking
/* A Naive recursive implementation
of 0-1 Knapsack problem */
#include <stdio.h>