Number of Moves in Python

Problem Statement:

Amir created a challenge where he have to calculate the total number of squares a bishop can move.
He knows the nxn size of the chessboard and the position of the bishop and the positions of the obstacles present on the chessboard.
The positions of the bishop and obstacles are denoted as rows and columns.
Help Amir for calculating the total number of moves, a bishop can take.

Note: A bishop can move diagonally i.e. diagonally top-left, top-right, bottom-left, and bottom-right from the current position. There’s no restriction over the distance it can move unless there’s not any obstacle present in the path.

Example:
Input1:
Enter N: 4
Enter the number of Obstacles: 2
Position of Bishop: 4 2
Positions of Obstacles:
2 4
3 1
Output1:
Number of moves: 1

Input2:
Enter N: 8
Enter the number of Obstacles: 5
Position of Bishop: 4 5
Positions of Obstacles:
1 2
2 7
6 5
7 8
8 1
Output2:
Number of moves: 8

Code for Number of Moves in Python:

'''calculate the number of squares a Bishop can move'''
def calculate_moves(bishop,obstacles,n):
    
    moves = 0
    
    #diagonal moves from the current position
    top_left =  [-1,-1]
    top_right = [-1,1]
    bottom_left =  [1,-1]
    bottom_right = [1,1]

    diagonals = [top_left,top_right,bottom_left,bottom_right]

    for diagonal in diagonals:
        #move bishop over every diagonal
        position = [bishop[0]+diagonal[0], bishop[1]+diagonal[1]]

        #check whether the position is valid and position is not of any obstacle else hault 
        while( (position[0]>=1 and position[0]<=n)  and (position[1]>=1 and position[1]<=n) and position not in obstacles):
            moves += 1
            position = [position[0]+diagonal[0],position[1]+diagonal[1]]
    
    return moves


'''input'''
n = int(input("Enter N: "))
k = int(input("Enter number of Obstacles: "))
bishop = list(map(int,input("Position of Bishop: ").split(" ")))

obstacles = list()

print("Positions of Obstacles: ")
for i in range(k):
    r,c = input().split(" ")
    obstacles.append([int(r),int(c)])

'''output'''
print("Number of moves: ",calculate_moves(bishop,obstacles,n))

Input1 and Output1:

Input1 and Output1 for Number of Moves in Python

Input2 and Output2:

Input2 and Output2 for Number of Moves in Python

Also Read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you