Knight - Possible Moves
Knight - Possible Moves
PROBLEM STATEMENT :
Example Input/Output 1:
Input: ()
B B B B B B H B
B B B B B B B B
B B B B B B B B
B B B B B B B B
B B B B B B B B
B B B B B B B B
B B B B B B B B
B B B B B B B B
Output:
3
Explanation:
The positions where the Knight can move are indicated by '*'.
B B B B * B B B
B B B B B * B *
B B B B B B B B
B B B B B B B B
B B B B B B B B
B B B B B B B B
As three moves are possible, 3 is printed as the output.
Example Input/Output 2:
Input: ()
B B B B B B B B
B B B B B B B B
B B B B B B B B
B B B H B B B B
B B B B B B B B
B B B B B B B B
B B B B B B B B
B B B B B B B B
Output:
8
1) LEARN THRICE
👇
2) THINK TWICE
👇
3) APPLY ONCE
SOLUTION :
C (Programming Language)
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[8][8];
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
scanf("%c ",&arr[i][j]);
}
}
int count=0;
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
if(arr[i][j]=='H')
{
int moves[8][2]={{-1,2},{1,2},{-1,-2},{1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
for(int k=0;k<8;k++)
{
if((i+moves[k][0])>=0 && (i+moves[k][0])<8 && (j+moves[k][1])>=0 && (j+moves[k][1])<8)
{
count++;
}
}
printf("%d",count);
return 0;
}
}
}
}
C++ (CPP)
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char** argv)
{
char arr[8][8];
int x, y;
for(int i=0; i<8; i++){
for(int j=0; j<8; j++){
cin >> arr[i][j];
if(arr[i][j]=='H'){
x=i;
y=j;
}
}
}
int dir[8][2]={{-1,-2},{-2,-1},{-1,2},{-2,1},{1,-2},{2,-1},{1,2},{2,1}};
int ans=0;
for(int i=0; i<8; i++){
int sr=x+dir[i][0], sc=y+dir[i][1];
if(sr<0 || sc<0 || sr>=8 || sc>=8) continue;
ans++;
}
cout << ans;
}
JAVA
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
char mat[][]=new char[8][8];
int kx=0;
int ky=0;
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
char ch=in.next().charAt(0);
mat[i][j]=ch;
if(ch=='H')
{
kx=i;ky=j;
}
}
}
int co=0;
int dir1[]={-2,-2,2,2,-1,-1,1,1};
int dir2[]={-1,1,-1,1,-2,2,-2,2};
for(int i=0;i<dir1.length;i++)
{
int nx=dir1[i]+kx;
int ny=dir2[i]+ky;
if(ny<0 || nx<0 || nx>=8 || ny>=8)
continue;
co++;
}
System.out.println(co);
}
}
PYTHON
L=[input().strip().split() for i in range(8)]
X=[[2,-1],[2,1],[-2,1],[-2,-1],[-1,2],[1,2],[-1,-2],[1,-2]]
for i in range(8):
for j in range(8):
if L[i][j]=='H':
TotalCount=0
for x,y in X:
if 0<=i+x<8 and 0<=j+y<8: TotalCount+=1
print(TotalCount)

Comments
Post a Comment