给定二维平面中的点(X,Y)和整数K ,任务是检查是否有可能以正好K的运动从(0,0)移至给定的点(X,Y) 。单步移动可从(X,Y)到达的位置是(X,Y + 1) , (X,Y – 1) , (X + 1,Y)和(X – 1,Y) 。
例子:
Input: X = 0, Y = 0, K = 2
Output: Yes
Move 1: (0, 0) -> (0, 1)
Move 2: (0, 1) -> (0, 0)
Input: X = 5, Y = 8, K = 20
Output: No
方法:显然,从(0,0 )到达(X,Y)的最短路径将是minMoves =(| X | + | Y |) 。因此,如果K
因此,只有当K≥(| X | + | Y |)和(K –(| X | + | Y |))%2 = 0时,才可能从(0,0 )达到(X,Y) 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that returns true if it is
// possible to move from (0, 0) to
// (x, y) in exactly k moves
bool isPossible(int x, int y, int k)
{
// Minimum moves required
int minMoves = abs(x) + abs(y);
// If possible
if (k >= minMoves && (k - minMoves) % 2 == 0)
return true;
return false;
}
// Driver code
int main()
{
int x = 5, y = 8, k = 20;
if (isPossible(x, y, k))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function that returns true if it is
// possible to move from (0, 0) to
// (x, y) in exactly k moves
static boolean isPossible(int x, int y, int k)
{
// Minimum moves required
int minMoves = Math.abs(x) + Math.abs(y);
// If possible
if (k >= minMoves && (k - minMoves) % 2 == 0)
return true;
return false;
}
// Driver code
public static void main (String[] args)
{
int x = 5, y = 8, k = 20;
if (isPossible(x, y, k))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function that returns true if it is
# possible to move from (0, 0) to
# (x, y) in exactly k moves
def isPossible(x, y, k):
# Minimum moves required
minMoves = abs(x) + abs(y)
# If possible
if (k >= minMoves and (k - minMoves) % 2 == 0):
return True
return False
# Driver code
x = 5
y = 8
k = 20
if (isPossible(x, y, k)):
print("Yes")
else:
print("No")
# This code is contributed by Mohit Kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function that returns true if it is
// possible to move from (0, 0) to
// (x, y) in exactly k moves
static bool isPossible(int x, int y, int k)
{
// Minimum moves required
int minMoves = Math.Abs(x) + Math.Abs(y);
// If possible
if (k >= minMoves && (k - minMoves) % 2 == 0)
return true;
return false;
}
// Driver code
public static void Main ()
{
int x = 5, y = 8, k = 20;
if (isPossible(x, y, k))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Nidhi
Javascript
输出:
No