📜  使用之字形方式从(0,0)到达点(x,y)所需的步数

📅  最后修改于: 2021-05-07 09:43:13             🧑  作者: Mango

给定坐标(x,y) 。任务是使用之字形方法计算从(0,0)到达点(x,y)所需的步数,并且直线行驶不能超过1个单位。另外,开始沿Y轴移动。
例如,我们可以按照下图所示的相应方式到达用红色表示的Point:

例子:

Input: x = 4, y = 4
Output: 8
In the diagram above the line is passing
using 8 steps.

Input: x = 4, y = 3
Output: 9

Input: x = 2, y = 1
Output: 5

方法:通过绘制一个小图,我们可以看到两种情况:

  • 情况1 :如果x小于y,则答案将始终为x + y + 2 *((yx)/ 2)
  • 情况2 :如果x大于y,则答案将始终为x + y + 2 *((((xy)+1)/ 2)

下面是上述方法的实现:

C++
// C++ program to find the number of steps
// required to reach (x, y) from (0, 0) following
// a zig-zag path
 
#include 
using namespace std;
 
// Function to return the required position
int countSteps(int x, int y)
{
    if (x < y) {
        return x + y + 2 * ((y - x) / 2);
    }
    else {
        return x + y + 2 * (((x - y) + 1) / 2);
    }
}
 
// Driver Code
int main()
{
    int x = 4, y = 3;
    cout << countSteps(x, y);
 
    return 0;
}


Java
// Java program to find the number of steps
// required to reach (x, y) from (0, 0) following
// a zig-zag path
 
class GfG
{
 
// Function to return the required position
static int countSteps(int x, int y)
{
    if (x < y)
    {
        return x + y + 2 * ((y - x) / 2);
    }
    else
    {
        return x + y + 2 * (((x - y) + 1) / 2);
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int x = 4, y = 3;
    System.out.println(countSteps(x, y));
}
}
 
// This code is contributed by Prerna Saini


Python3
# Python3 program to find the number of
# steps required to reach (x, y) from
# (0, 0) following a zig-zag path
   
# Function to return the required position
def countSteps(x, y):
  
    if x < y:
        return x + y + 2 * ((y - x) // 2)
      
    else:
        return x + y + 2 * (((x - y) + 1) // 2)
 
# Driver Code
if __name__ == "__main__":
  
    x, y = 4, 3
    print(countSteps(x, y))
   
# This code is contributed by Rituraj Jain


C#
// C# program to find the number of steps
// required to reach (x, y) from (0, 0) 
// following a zig-zag path
using System;
 
class GfG
{
 
// Function to return the required position
static int countSteps(int x, int y)
{
    if (x < y)
    {
        return x + y + 2 * ((y - x) / 2);
    }
    else
    {
        return x + y + 2 * (((x - y) + 1) / 2);
    }
}
 
// Driver Code
public static void Main()
{
    int x = 4, y = 3;
    Console.WriteLine(countSteps(x, y));
}
}
 
// This code is contributed by Code_Mech.


PHP


Javascript


输出:
9

时间复杂度: O(1)