- Related Questions & Answers
- 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 find minimum number of hops required to reach end position in Python
- Program to check robot can reach target position or not in Python
- Program to find minimum cost to reach final index with at most k steps in python
- Find minimum steps required to reach the end of a matrix in C++
- Find minimum moves to reach target on an infinite line in C++
- 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
- Find the minimum number of steps to reach M from N in C++
- Program to find minimum distance to the target element using Python
- Program to find intervals by merging target interval in Python
- Program to check robot can reach target by keep moving on visited spots in Python
- Program to Find Minimum Jumps Required to Reach a Value with Different Parity in Python
- Program to find minimum number of vertices to reach all nodes using Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

6, 1

3

Advertisements