📌  相关文章
📜  计算通过向前或向后移动给定步数可以到达的唯一楼梯

📅  最后修改于: 2021-10-25 05:12:26             🧑  作者: Mango

给定一个整数N ,代表楼梯的数量,值从1N ,以及一个起始位置S ,任务是计算可以通过准确地向前或向后移动AB楼梯步骤到达的唯一楼梯的最大数量任何位置,任何次数。

例子:

方法:给定的问题可以使用 BFS 遍历技术解决。请按照以下步骤解决问题:

  • 初始化一个队列和一个大小为(N + 1)的数组vis[]并将其初始化为false
  • 将起始节点S标记为已访问,即vis[S]1 。将S推入队列Q
  • 现在迭代直到Q不为空并执行以下步骤:
    • 弹出队列的前端元素并将其存储在一个变量中,比如currStair
    • 考虑来自currStair 的所有 4 种可能的移动类型{+A, -A, +B, -B}
    • 对于每一个新楼梯,检查它是否是一个有效且未被访问过的楼梯。如果发现为真,则将其推入Q 将楼梯标记为已访问。否则,继续。
  • 最后,使用数组vis[]计算已访问楼梯的数量。
  • 完成上述步骤后,打印访问楼梯的数量作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count the number
// of unique stairs visited
void countStairs(int n, int x, int a, int b)
{
    // Checks whether the current
    // stair is visited or not
    int vis[n + 1] = { 0 };
 
    // Store the possible moves
    // from the current position
    int moves[] = { +a, -a, +b, -b };
 
    // Initialize a queue
    queue q;
 
    /// Push the starting position
    q.push(x);
 
    // Mark the starting
    // position S as visited
    vis[x] = 1;
 
    // Interate until queue is not empty
    while (!q.empty()) {
 
        // Store the current stair number
        int currentStair = q.front();
 
        // Pop it from the queue
        q.pop();
 
        // Check for all possible moves
        // from the current stair
        for (int j = 0; j < 4; j++) {
 
            // Store the new stair number
            int newStair = currentStair + moves[j];
 
            // If it is valid and unvisited
            if (newStair > 0 && newStair <= n
                && !vis[newStair]) {
 
                // Push it into queue
                q.push(newStair);
 
                // Mark the stair as visited
                vis[newStair] = 1;
            }
        }
    }
 
    // Store the result
    int cnt = 0;
 
    // Count the all visited stairs
    for (int i = 1; i <= n; i++)
        if (vis[i] == 1)
            cnt++;
 
    // Print the result
    cout << cnt;
}
 
// Driver Code
int main()
{
    int N = 10, S = 2, A = 5, B = 7;
    countStairs(N, S, A, B);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.LinkedList;
import java.util.Queue;
 
class GFG{
 
// Function to count the number
// of unique stairs visited
static void countStairs(int n, int x, int a, int b)
{
     
    // Checks whether the current
    // stair is visited or not
    int[] vis = new int[n + 1];
 
    // Store the possible moves
    // from the current position
    int[] moves = { +a, -a, +b, -b };
 
    // Initialize a queue
    Queue q = new LinkedList();
 
    /// Push the starting position
    q.add(x);
 
    // Mark the starting
    // position S as visited
    vis[x] = 1;
 
    // Interate until queue is not empty
    while (!q.isEmpty())
    {
         
        // Store the current stair number
        int currentStair = q.peek();
 
        // Pop it from the queue
        q.remove();
 
        // Check for all possible moves
        // from the current stair
        for(int j = 0; j < 4; j++)
        {
             
            // Store the new stair number
            int newStair = currentStair + moves[j];
 
            // If it is valid and unvisited
            if (newStair > 0 && newStair <= n &&
                            vis[newStair] == 0)
            {
                 
                // Push it into queue
                q.add(newStair);
 
                // Mark the stair as visited
                vis[newStair] = 1;
            }
        }
    }
 
    // Store the result
    int cnt = 0;
 
    // Count the all visited stairs
    for(int i = 1; i <= n; i++)
        if (vis[i] == 1)
            cnt++;
 
    // Print the result
    System.out.print(cnt);
}
 
// Driver Code
public static void main(String args[])
{
    int N = 10, S = 2, A = 5, B = 7;
 
    countStairs(N, S, A, B);
}
}
 
// This code is contributed by abhinavjain194


Python3
# Python3 program for the above approach
from collections import deque
 
# Function to count the number
# of unique stairs visited
def countStairs(n, x, a, b):
     
    # Checks whether the current
    # stair is visited or not
    vis = [0] * (n + 1)
 
    # Store the possible moves
    # from the current position
    moves = [+a, -a, +b, -b]
 
    # Initialize a queue
    q = deque()
 
    # Push the starting position
    q.append(x)
 
    # Mark the starting
    # position S as visited
    vis[x] = 1
 
    # Interate until queue is not empty
    while (len(q) > 0):
 
        # Store the current stair number
        currentStair = q.popleft()
 
        # Pop it from the queue
        # q.pop()
 
        # Check for all possible moves
        # from the current stair
        for j in range(4):
 
            # Store the new stair number
            newStair = currentStair + moves[j]
 
            # If it is valid and unvisited
            if (newStair > 0 and newStair <= n and
               (not vis[newStair])):
                # Push it into queue
                q.append(newStair)
 
                # Mark the stair as visited
                vis[newStair] = 1
 
    # Store the result
    cnt = 0
 
    # Count the all visited stairs
    for i in range(1, n + 1):
        if (vis[i] == 1):
            cnt += 1
 
    # Print the result
    print (cnt)
 
# Driver Code
if __name__ == '__main__':
     
    N, S, A, B = 10, 2, 5, 7
     
    countStairs(N, S, A, B)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
  
// Function to count the number
// of unique stairs visited
static void countStairs(int n, int x,
                        int a, int b)
{
     
    // Checks whether the current
    // stair is visited or not
    int []vis = new int[n + 1];
    Array.Clear(vis, 0, vis.Length);
 
    // Store the possible moves
    // from the current position
    int []moves = { +a, -a, +b, -b };
 
    // Initialize a queue
    Queue q = new Queue();
 
    /// Push the starting position
    q.Enqueue(x);
 
    // Mark the starting
    // position S as visited
    vis[x] = 1;
 
    // Interate until queue is not empty
    while (q.Count > 0)
    {
         
        // Store the current stair number
        int currentStair = q.Peek();
 
        // Pop it from the queue
        q.Dequeue();
 
        // Check for all possible moves
        // from the current stair
        for(int j = 0; j < 4; j++)
        {
             
            // Store the new stair number
            int newStair = currentStair + moves[j];
 
            // If it is valid and unvisited
            if (newStair > 0 && newStair <= n &&
                            vis[newStair] == 0)
            {
                 
                // Push it into queue
                q.Enqueue(newStair);
 
                // Mark the stair as visited
                vis[newStair] = 1;
            }
        }
    }
 
    // Store the result
    int cnt = 0;
 
    // Count the all visited stairs
    for(int i = 1; i <= n; i++)
        if (vis[i] == 1)
            cnt++;
 
    // Print the result
    Console.WriteLine(cnt);
}
 
// Driver Code
public static void Main()
{
    int N = 10, S = 2, A = 5, B = 7;
     
    countStairs(N, S, A, B);
}
}
 
// This code is contributed by ipg2016107


Javascript


输出:
4

时间复杂度: O(N)
辅助空间: O(N)