0% found this document useful (0 votes)
5 views

ADA Lab Manual-3

The document contains multiple C/C++ programs that implement various graph algorithms, including Kruskal's and Prim's algorithms for finding Minimum Cost Spanning Trees, Floyd's algorithm for All-Pairs Shortest Paths, Warshall's algorithm for transitive closure, Dijkstra's algorithm for shortest paths, and a method for Topological sorting. Each program includes the necessary data structures and functions to perform the respective algorithm, along with example input and output. The algorithms are designed to work with connected undirected graphs and directed graphs.

Uploaded by

Geetha.R Achar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

ADA Lab Manual-3

The document contains multiple C/C++ programs that implement various graph algorithms, including Kruskal's and Prim's algorithms for finding Minimum Cost Spanning Trees, Floyd's algorithm for All-Pairs Shortest Paths, Warshall's algorithm for transitive closure, Dijkstra's algorithm for shortest paths, and a method for Topological sorting. Each program includes the necessary data structures and functions to perform the respective algorithm, along with example input and output. The algorithms are designed to work with connected undirected graphs and directed graphs.

Uploaded by

Geetha.R Achar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

1.

Design and implement C/C++ Program to find Minimum Cost Spanning


Tree of a given connected undirected graph using Kruskal's algorithm.
#include <stdio.h>
#include <stdlib.h>
#define MAX_EDGES 1000
typedef struct Edge {
int src, dest, weight;
} Edge;
typedef struct Graph {
int V, E;
Edge edges[MAX_EDGES];
} Graph;
typedef struct Subset {
int parent, rank;
} Subset;
Graph* createGraph(int V, int E) {
Graph* graph = (Graph*) malloc(sizeof(Graph));
graph->V = V;
graph->E = E;
return graph;
}
int find(Subset subsets[], int i) {
if (subsets[i].parent != i) {
subsets[i].parent = find(subsets, subsets[i].parent);
}
return subsets[i].parent;
}
void Union(Subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank) {
subsets[xroot].parent = yroot;
} else if (subsets[xroot].rank > subsets[yroot].rank) {
subsets[yroot].parent = xroot;
} else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
int compare(const void* a, const void* b) {
Edge* a_edge = (Edge*) a;
Edge* b_edge = (Edge*) b;
return a_edge->weight - b_edge->weight;
}
void kruskalMST(Graph* graph) {
Edge mst[graph->V];
int e = 0, i = 0;
qsort(graph->edges, graph->E, sizeof(Edge), compare);
Subset* subsets = (Subset*) malloc(graph->V * sizeof(Subset));
for (int v = 0; v < graph->V; ++v) {
subsets[v].parent = v;
subsets[v].rank = 0;
}
while (e < graph->V - 1 && i < graph->E) {
Edge next_edge = graph->edges[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
mst[e++] = next_edge;
Union(subsets, x, y);
}
}
printf("Minimum Spanning Tree:\n");
for (i = 0; i < e; ++i) {
printf("(%d, %d) -> %d\n", mst[i].src, mst[i].dest, mst[i].weight);
}
}
int main() {
int V, E;
printf("Enter number of vertices and edges: ");
scanf("%d %d", &V, &E);
Graph* graph = createGraph(V, E);
printf("Enter edges and their weights:\n");
for (int i = 0; i < E; ++i) {
scanf("%d %d %d", &graph->edges[i].src, &graph->edges[i].dest, &graph-
>edges[i].weight);
}
kruskalMST(graph);
return 0;
}
OUTPUT

2. Design and implement C/C++ Program to find Minimum Cost Spanning


Tree of a given connected undirected graph using Prim's algorithm.
#include <stdio.h>
#include <limits.h>
#define vertices 5 /*Define the number of vertices in the graph*/
/* create minimum_key() method for finding the vertex that has minimum key-value and that
is not added in MST yet */
int minimum_key(int k[], int mst[])
{
int minimum = INT_MAX, min,i;
/*iterate over all vertices to find the vertex with minimum key-value*/
for (i = 0; i < vertices; i++)
if (mst[i] == 0 && k[i] < minimum )
minimum = k[i], min = i;
return min;
}
/* create prim() method for constructing and printing the MST.
The g[vertices][vertices] is an adjacency matrix that defines the graph for MST.*/
void prim(int g[vertices][vertices])
{
/* create array of size equal to total number of vertices for storing the MST*/
int parent[vertices];
/* create k[vertices] array for selecting an edge having minimum weight*/
int k[vertices];
int mst[vertices];
int i, count,edge,v; /*Here 'v' is the vertex*/
for (i = 0; i < vertices; i++)
{
k[i] = INT_MAX;
mst[i] = 0;
}
k[0] = 0; /*It select as first vertex*/
parent[0] = -1; /* set first value of parent[] array to -1 to make it root of MST*/
for (count = 0; count < vertices-1; count++)
{
/*select the vertex having minimum key and that is not added in the MST yet from the set
of vertices*/
edge = minimum_key(k, mst);
mst[edge] = 1;
for (v = 0; v < vertices; v++)
{
if (g[edge][v] && mst[v] == 0 && g[edge][v] < k[v])
{
parent[v] = edge, k[v] = g[edge][v];
}
}
}
/*Print the constructed Minimum spanning tree*/
printf("\n Edge \t Weight\n");
for (i = 1; i < vertices; i++)
printf(" %d <-> %d %d \n", parent[i], i, g[i][parent[i]]);
}
int main()
{
int g[vertices][vertices] = {{0, 0, 3, 0, 0},
{0, 0, 10, 4, 0},
{3, 10, 0, 2, 6},
{0, 4, 2, 0, 1},
{0, 0, 6, 1, 0},
};
prim(g);
return 0;
}
OUTPUT

3a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths
problem using Floyd's algorithm.
#include<stdio.h>
// Number of vertices in the graph
#define V 4
// A function to print the solution matrix
void printSolution(int dist[][V]);
void floydWarshall (int graph[][V])
{
int dist[V][V], i, j, k;
// Initialize the solution matrix same as input graph matrix.
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
// Update the solution matrix by picking all vertices one by one
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
// If vertex k is on the shortest path from i to j,
// then update the value of dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
printSolution(dist);
}
void printSolution(int dist[][V])
{
printf ("Following matrix shows the shortest distances between every pair of vertices \n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (dist[i][j] == 9999)
printf("%7s", "INF");
else
printf ("%7d", dist[i][j]);
}
printf("\n");
}
}
int main()
{
int graph[V][V] = { {0, 5, 9999, 10},
{9999, 0, 3, 9999},
{9999, 9999, 0, 1},
{9999, 9999, 9999, 0}
};

floydWarshall(graph);
return 0;
}
OUTPUT
3b.Design and implement C/C++ Program to find the transitive closure using
Warshal's algorithm
#include<stdio.h>
#include<math.h>
int max(int,int);
void warshal(int p[10][10],int n) {
int i,j,k;
for (k=1;k<=n;k++)
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
p[i][j]=max(p[i][j],p[i][k]&&p[k][j]);
}
int max(int a,int b) {
if(a>b)
return(a);
else
return(b);
}
void main() {
int p[10][10]= {0},n,e,u,v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:");
scanf("%d",&e);
for (i=1;i<=e;i++) {
printf("\n Enter the end vertices of edge %d:",i);
scanf("%d%d",&u,&v);
p[u][v]=1;
}
printf("\n Matrix of input data: \n");
for (i=1;i<=n;i++) {
for (j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
warshal(p,n);
printf("\n Transitive closure: \n");
for (i=1;i<=n;i++) {
for (j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
}
OUTPUT

4.Design and implement C/C++ Program to find shortest paths from a given
vertex in a weighted connected graph to other vertices using Dijkstra's
algorithm.
/#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
// Number of vertices in the graph
#define V 9
// A utility function to find the vertex with minimum
// distance value, from the set of vertices not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// A utility function to print the constructed distance
// array
void printSolution(int dist[])
{
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}
// Function that implements Dijkstra's single source
// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the shortest distance from src to i
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = true;
// Update dist value of the adjacent vertices of the
// picked vertex.
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
// print the constructed distance array
printSolution(dist);
}
// driver's code
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

// Function call
dijkstra(graph, 0);
return 0;
}
OUTPUT
5.Design and implement C/C++ Program to obtain the Topological ordering
of vertices in a given digraph.
// C Program to implement Topological Sorting
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// Structure to represent a stack
struct Stack {
int data;
struct Stack* next;
};
struct Graph {
int V; // No. of vertices
// Pointer to an array containing adjacency lists
struct List* adj;
};
// Structure to represent a list (adjacency list)
struct List {
int data;
struct List* next;
};
// Create a new node for the stack
struct Stack* createStackNode(int data)
{
struct Stack* newNode
= (struct Stack*)malloc(sizeof(struct Stack));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Create a new node for the adjacency list
struct List* createListNode(int data)
{
struct List* newNode
= (struct List*)malloc(sizeof(struct List));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to initialize a graph with V vertices
struct Graph* createGraph(int V)
{
struct Graph* graph
= (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->adj
= (struct List*)malloc(V * sizeof(struct List));
for (int i = 0; i < V; ++i) {
graph->adj[i].next = NULL;
}
return graph;
}
// Function to add an edge to the graph
void addEdge(struct Graph* graph, int v, int w)
{
struct List* newNode = createListNode(w);
newNode->next = graph->adj[v].next;
graph->adj[v].next = newNode;
}
// A recursive function used by topologicalSort
void topologicalSortUtil(struct Graph* graph, int v,
bool visited[],
struct Stack** stack)
{
visited[v] = true;
struct List* current = graph->adj[v].next;
while (current != NULL) {
int adjacentVertex = current->data;
if (!visited[adjacentVertex]) {
topologicalSortUtil(graph, adjacentVertex,
visited, stack);
}
current = current->next;
}
// Push the current vertex to stack which stores the
// result
struct Stack* newNode = createStackNode(v);
newNode->next = *stack;
*stack = newNode;
}
// The function to do Topological Sort. It uses recursive
// topologicalSortUtil
void topologicalSort(struct Graph* graph)
{
struct Stack* stack = NULL;
// Mark all the vertices as not visited
bool* visited = (bool*)malloc(graph->V * sizeof(bool));
for (int i = 0; i < graph->V; ++i) {
visited[i] = false;
}
// Call the recursive helper function to store
// Topological Sort starting from all vertices one by
// one
for (int i = 0; i < graph->V; ++i) {
if (!visited[i]) {
topologicalSortUtil(graph, i, visited, &stack);
}
}

// Print contents of stack


while (stack != NULL) {
printf("%d ", stack->data);
struct Stack* temp = stack;
stack = stack->next;
free(temp);
}
// Free allocated memory
free(visited);
free(graph->adj);
free(graph);
}
// Driver program to test above functions
int main()
{
// Create a graph given in the above diagram
struct Graph* g = createGraph(6);
addEdge(g, 5, 2);
addEdge(g, 5, 0);
addEdge(g, 4, 0);
addEdge(g, 4, 1);
addEdge(g, 2, 3);
addEdge(g, 3, 1);
printf("Topological Sorting Order: ");
topologicalSort(g);
return 0;
}
OUTPUT
6.Design and implement C/C++ Program to solve 0/1 Knapsack problem
using Dynamic Programming method.
#include <stdio.h>
int max(int a, int b) { return (a > b) ? a : b; }
int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);
else
return max( val[n - 1]+ knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
// Driver code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("%d", knapSack(W, weight, profit, n));
return 0;
}
OUTPUT
7. Design and implement C/C++ Program to solve discrete Knapsack and
continuous Knapsack problems using greedy approximation method.
#include<stdio.h>
int main()
{
float weight[50],profit[50],ratio[50],Totalvalue,temp,capacity,amount;
int n,i,j;
printf("Enter the number of items :");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
printf("Enter Weight and Profit for item[%d] :\n",i);
scanf("%f %f", &weight[i], &profit[i]);
}
printf("Enter the capacity of knapsack :\n");
scanf("%f",&capacity);
for(i=0;i<n;i++)
ratio[i]=profit[i]/weight[i];
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (ratio[i] < ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
printf("Knapsack problems using Greedy Algorithm:\n");
for (i = 0; i < n; i++)
{
if (weight[i] > capacity)
break;
else
{
Totalvalue = Totalvalue + profit[i];
capacity = capacity - weight[i];
}
}
if (i < n)
Totalvalue = Totalvalue + (ratio[i]*capacity);
printf("\nThe maximum value is :%f\n",Totalvalue);
return 0;
}
OUTPUT
8.Design and implement C/C++ Program to find a subset of a given set S =
{sl , s2,.....,sn} of n positive integers whose sum is equal to a given positive
integer d.
#include <stdio.h>
#include <stdbool.h>
bool isSubsetSum(int set[], int n, int sum)
{
// Base Cases
if (sum == 0)
return true;
if (n == 0)
return false;
if (set[n - 1] > sum)
return isSubsetSum(set, n - 1, sum);
return isSubsetSum(set, n - 1, sum)
|| isSubsetSum(set, n - 1, sum - set[n - 1]);
}
// Driver code
int main()
{
int set[] = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
int n = sizeof(set) / sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true)
printf("Found a subset with given sum");
else
printf("No subset with given sum");
return 0;
}
OUTPUT
9. Design and implement C/C++ Program to sort a given set of n integer
elements using Selection Sort method and compute its time complexity. Run
the program for varied values of n> 5000 and record the time taken to sort.
Plot a graph of the time taken versus n. The elements can be read from a file
or can be generated using the random number generator.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Selection Sort function


void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}

// Function to generate an array of random integers


void generateRandomArray(int arr[], int n) {
srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand();
}
}

int main() {
int n_values[] = {5000, 10000, 15000, 20000}; // Array of n values
int num_values = sizeof(n_values) / sizeof(n_values[0]);
double time_taken[num_values];

for (int i = 0; i < num_values; i++) {


int n = n_values[i];
int *arr = (int*)malloc(n * sizeof(int));
generateRandomArray(arr, n);

clock_t start = clock();


selectionSort(arr, n);
clock_t end = clock();

time_taken[i] = ((double)(end - start)) / CLOCKS_PER_SEC;


free(arr);
}

// Output time taken for sorting each value of n


printf("n\tTime Taken (s)\n");
for (int i = 0; i < num_values; i++) {
printf("%d\t%f\n", n_values[i], time_taken[i]);
}

// Plotting the graph can be done using external tools like gnuplot, matplotlib, etc.

return 0;
}
10.Design and implement C/C++ Program to sort a given set of n integer
elements using Quick Sort method and compute its time complexity. Run the
program for varied values of n> 5000 and record the time taken to sort. Plot
a graph of the time taken versus n. The elements can be generated using the
random number generator.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function prototypes
void quickSort(int arr[], int low, int high);
int partition(int arr[], int low, int high);
void swap(int *a, int *b);
void generateRandomArray(int arr[], int n);
double calculateTimeTaken(clock_t start, clock_t end);
int main() {
int n_values[] = {5000, 10000, 15000, 20000}; // Array of n values
int num_values = sizeof(n_values) / sizeof(n_values[0]);
clock_t start, end;
double time_taken[num_values];
for (int i = 0; i < num_values; i++) {
int n = n_values[i];
int *arr = (int*)malloc(n * sizeof(int));
generateRandomArray(arr, n);
start = clock();
quickSort(arr, 0, n - 1);
end = clock();
time_taken[i] = calculateTimeTaken(start, end);
free(arr);
}

// Output time taken for sorting each value of n


printf("n\tTime Taken (s)\n");
for (int i = 0; i < num_values; i++) {
printf("%d\t%f\n", n_values[i], time_taken[i]);
}
// Plotting the graph can be done using external tools like gnuplot, matplotlib, etc.
return 0;
}

// Quick Sort function


void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


quickSort(arr, pi + 1, high);
}
}

// Partition function
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; j++) {


if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

// Utility function to swap two elements


void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Function to generate an array of random integers


void generateRandomArray(int arr[], int n) {
srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand();
}
}

// Function to calculate time taken


double calculateTimeTaken(clock_t start, clock_t end) {
return ((double)(end - start)) / CLOCKS_PER_SEC;
}
OUTPUT

11. Design and implement C/C++ Program to sort a given set of n integer
elements using Merge Sort method and compute its time complexity. Run the
program for varied values of n> 5000, and record the time taken to sort. Plot
a graph of the time taken versus n. The elements can be read from a file or
can be generated using the random number generator.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Merge function to merge two sorted subarrays


void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Create temporary arrays


int L[n1], R[n2];

// Copy data to temporary arrays L[] and R[]


for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

// Merge the temporary arrays back into arr[l..r]


i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if any


while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Merge Sort function


void mergeSort(int arr[], int l, int r) {
if (l < r) {
// Same as (l+r)/2, but avoids overflow for large l and h
int m = l + (r - l) / 2;

// Sort first and second halves


mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted halves


merge(arr, l, m, r);
}
}

// Function to generate an array of random integers


void generateRandomArray(int arr[], int n) {
srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand();
}
}

int main() {
int n_values[] = {5000, 10000, 15000, 20000}; // Array of n values
int num_values = sizeof(n_values) / sizeof(n_values[0]);
double time_taken[num_values];

for (int i = 0; i < num_values; i++) {


int n = n_values[i];
int *arr = (int*)malloc(n * sizeof(int));
generateRandomArray(arr, n);

clock_t start = clock();


mergeSort(arr, 0, n - 1);
clock_t end = clock();

time_taken[i] = ((double)(end - start)) / CLOCKS_PER_SEC;


free(arr);
}

// Output time taken for sorting each value of n


printf("n\tTime Taken (s)\n");
for (int i = 0; i < num_values; i++) {
printf("%d\t%f\n", n_values[i], time_taken[i]);
}

// Plotting the graph can be done using external tools like gnuplot, matplotlib, etc.

return 0;
}

12.Design and implement C/C++ Program for N Queen's problem using


Backtracking.
#define N 4
#include <stdbool.h>
#include <stdio.h>
// 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");
}
}
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
// Check this row on left side
for (i = 0; i < col; i++)
if (board[row][i])
return false;
// Check upper diagonal on left side
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
// Check lower diagonal on left side
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;
return true;
}
// A recursive utility function to solve N
// Queen problem
bool solveNQUtil(int board[N][N], int col)
{
// Base case: If all queens are placed
// then return true
if (col >= N)
return true;
// Consider this column and try placing
// this queen in all rows one by one
for (int i = 0; i < N; i++) {
// Check if the queen can be placed on
// board[i][col]
if (isSafe(board, i, col)) {

// Place this queen in board[i][col]


board[i][col] = 1;
// Recur to place rest of the queens
if (solveNQUtil(board, col + 1))
return true;
// If placing queen in board[i][col]
// doesn't lead to a solution, then
// remove queen from board[i][col]
board[i][col] = 0; // BACKTRACK
}
}
// If the queen cannot be placed in any row in
// this column col then return false
return false;
}
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

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;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy