Skip to content

Commit 3b232eb

Browse files
authored
Merge pull request #631 from Jayshree-2111/DevIncept1
N_Queens Problem using C
2 parents eb28814 + 98a8845 commit 3b232eb

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution //Solution Class
2+
{
3+
public:
4+
void rotate(vector<int>& nums, int k) //function for shifting the elements
5+
{
6+
int n = nums.size(); //assign size of array
7+
int start = n - k % n; //starting from first element
8+
int remainder = k % n; //to move to next index
9+
vector<int> v(n);
10+
11+
for(int i = 0; i < remainder; i++) //shifting the index
12+
{
13+
v[i] = nums[i + start];
14+
}
15+
16+
for(int i = 0; i < start; i++) //shifting the index
17+
{
18+
v[i + remainder] = nums[i];
19+
}
20+
21+
for(int i = 0; i < n; i++) //for shifting elements
22+
{
23+
nums[i] = v[i];
24+
}
25+
}
26+
};
27+

Backtracking/N_Queens Problem.c

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/* The N Queen is the problem of placing N chess queens on an
2+
N×N chessboard so that no two queens attack each other.
3+
4+
Language Used: C language
5+
6+
Output: The expected output is a binary matrix which has numbers
7+
for the blocks where queens are placed.
8+
9+
For example, following is the output matrix for above 4 queen solution.
10+
OUTPUT FOR 4 Queens: { 2, 4, 1, 3}
11+
{ 3, 1, 4, 2}
12+
*/
13+
#include<stdio.h>
14+
#include<stdlib.h>
15+
#include<conio.h>
16+
#include<math.h>
17+
18+
int place(int r,int c,int x[])//function gives resultant appropriate place for the queen
19+
{
20+
int i;
21+
for(i=1; i<r; i++)
22+
{
23+
if(x[i]==c||(abs(x[i]-c)==abs(i-r)))
24+
return 0;
25+
}
26+
return 1;
27+
}
28+
29+
void NQueen(int r,int n,int x[]) //function for checking the places of the queen so that one queen would not attack other
30+
{
31+
int c,i;
32+
for(c=1; c<=n; c++)
33+
{
34+
if(place(r,c,x))
35+
{
36+
x[r]=c;
37+
if(r==n)
38+
{
39+
printf("{");
40+
for(i=1; i<=n; i++)
41+
printf(" %d",x[i]);
42+
printf(" }\n");
43+
}
44+
else
45+
NQueen(r+1,n,x);
46+
}
47+
}
48+
}
49+
int main()
50+
{
51+
int n,i,j;
52+
int x[50];
53+
printf("\nEnter the no. of Queens: ");
54+
scanf("%d",&n);
55+
printf("\nResultant Places of Queens: \n");
56+
NQueen(1,n,x);
57+
}

0 commit comments

Comments
 (0)