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

📅  最后修改于: 2021-10-23 08:03:35             🧑  作者: Mango

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

例子:

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)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程