Positions - Queen & Knight (Greedy Algorithm)
Positions - Queen & Knight (Greedy Algorithm)
PROBLEM STATEMENT :
Given a position of Queen and Knight. Form 8X8 matrix with all position filled with '0' and replace given Queen position with 'Q' and replace given Knight position with 'K'. Find number of possible moves where Queen can be moved on a chessboard from given position and replace the positions with 'q' and Find number of possible moves where Knight can be moved on a chessboard from given position and replace the positions with 'k' and if both queen and knight meets in same position then that position should be replaced with 'x'.
First line consist of row and column position of Queen
First line consist of row and column position of Knight
8X8 matrix with all possible moves of Queen and Knight.
Example Input/Output 1:
Input: ()
2 3
4 8
Output:
0 q q q 0 0 0 0
q q Q q q q x q
0 q q q 0 k 0 0
q 0 q 0 q 0 0 K
0 0 q 0 0 x 0 0
0 0 q 0 0 0 x 0
0 0 q 0 0 0 0 q
0 0 q 0 0 0 0 0Example Input/Output 2:
Input: ()
3 2
4 8
Output:
0 q 0 q 0 0 0 0
q q q 0 0 0 k 0
q Q q q q x q q
q q q 0 0 0 0 K
0 q 0 q 0 k 0 0
0 q 0 0 q 0 k 0
0 q 0 0 0 q 0 0
0 q 0 0 0 0 q 0SOLUTION : (CPP)
#include <iostream>
#include<string.h> //For memset function
using namespace std;
int main()
{
char a[8][8];
memset(a,'0',sizeof(a)); //For setting matrix values to '0'
int qx,qy,kx,ky,i,j,x;
cin>>qx>>qy>>kx>>ky;
qx--;
qy--;
kx--;
ky--;
a[qx][qy]='Q';
a[kx][ky]='K';
int a1[]={1,1,1,0,0,-1,-1,-1};
int a2[]={1,0,-1,1,-1,1,0,-1};
for(x=0;x<8;++x)
{
i=qx+a1[x];
j=qy+a2[x];
while(i>=0&&i<8&&j>=0&&j<8)
{
a[i][j]='q';
i+=a1[x];
j+=a2[x];
}
}
int b1[]={2,2,-2,-2,1,1,-1,-1};
int b2[]={1,-1,1,-1,2,-2,2,-2};
for(x=0;x<8;++x)
{
i=kx+b1[x];
j=ky+b2[x];
if(i>=0&&i<8&&j>=0&&j<8)
{
if(a[i][j]=='Q') continue;
else if(a[i][j]=='q') a[i][j]='x';
else a[i][j]='k';
}
}
for(i=0;i<8;++i)
{
for(j=0;j<8;++j)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
Comments
Post a Comment