
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find minimum steps to reach target position by a chess knight in Python
Suppose we have two values r and c. If a chess knight is placed at the coordinate (0, 0) at the beginning in an infinitely large chess board, we have to find minimum number of moves it would take to reach the location (r, c). The knight will follow same moving style as chess. It moves two squares away horizontally and one square vertically, or two squares vertically and one square horizontally.
So, if the input is like r = 6, c = 1, then the output will be 3, the red is initial position, green is final and yellows are intermediate steps.
To solve this, we will follow these steps −
- if r < c, then
- swap r and c
- if (r, c) is same as (1, 0), then
- return 3
- if (r, c) is same as (2, 2), then
- return 4
- delta := r - c
- if c > delta, then
- return delta - 2 *(quotient of (delta - c) / 3)
- otherwise,
- return delta - 2 *(quotient of (delta - c) / 4)
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, r, c): if r < c: r, c = c, r if (r, c) == (1, 0): return 3 if (r, c) == (2, 2): return 4 delta = r - c if c > delta: return delta - 2 * ((delta - c) // 3) else: return delta - 2 * ((delta - c) // 4) ob = Solution() r = 6 c = 1 print(ob.solve(r, c))
Input
6, 1
Output
3
- Related Articles
- Program to find out the minimum number of moves for a chess piece to reach every position in Python
- How to find the minimum number of steps needed by knight to reach the destination using C#?
- Program to find number of minimum steps to reach last index in Python
- Program to find minimum number of buses required to reach final target in python
- Program to check robot can reach target position or not in Python
- Program to find minimum number of hops required to reach end position in Python
- Program to find minimum cost to reach final index with at most k steps in python
- Program to find number of optimal steps needed to reach destination by baby and giant steps in Python
- C++ code to count steps to reach final position by robot
- Program to find minimum jumps to reach home in Python
- Program to find number of given operations required to reach Target in Python
- Program to find number of combinations of coins to reach target in Python
- C++ program to find minimum number of punches are needed to make way to reach target
- Find minimum moves to reach target on an infinite line in C++
- Find minimum steps required to reach the end of a matrix in C++

Advertisements