给定两个整数S和T以及一个数组arr ,其中以未排序的方式包含从1到N的元素。任务是通过以下操作找到将Sth元素移动到数组中的Tth位置的最小移动次数:
一招包括以下内容
// Initially b[] = {1, 2, 3, ..., N}
// arr[] is input array
for (i = 1..n)
temp[arr[i]] = b[i]
b = temp
如果不可能,请打印-1 。
例子:
Input: S = 2, T = 1, arr[] = {2, 3, 4, 1}
Output: 3
N is 4 (size of arr[])
Move 1: b[] = {4, 1, 2, 3}
Move 2: b[] = {3, 4, 1, 2}
Move 3: b[] = {2, 3, 4, 1}
Input: S = 3, T = 4, arr[] = {1, 2, 3, 4}
Output: -1
N is 4 (Size of arr[])
Regardless of how many moves are made, the permutation would remain the same.
方法:这里重要的观察结果是,我们只关注单个元素的位置,而不关注整个数组的位置。因此,在每次移动时,我们都将位置S的元素移动到位置arr [S] ,直到达到Tth位置。
由于我们最多可以到达N个不同的位置,因此,如果我们在N个动作中没有到达T ,则意味着我们永远也无法到达。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the number of moves
int minimumMoves(int n, int a[], int s, int t)
{
int i, x;
x = s;
for (i = 1; i <= n; i++) {
if (x == t)
break;
x = a[x];
}
// Destination reached
if (x == t)
return i - 1;
else
return -1;
}
// Driver Code
int main()
{
int s = 2, t = 1, i;
int a[] = {-1, 2, 3, 4, 1};
int n = sizeof(a) / sizeof(a[0]);
cout << minimumMoves(n, a, s, t);
}
Java
// Java implementation of the approach
public class GFG{
// Function to return the number of moves
static int minimumMoves(int n, int a[], int s, int t)
{
int i, x;
x = s;
for (i = 1; i <= n; i++) {
if (x == t)
break;
x = a[x];
}
// Destination reached
if (x == t)
return i - 1;
else
return -1;
}
// Driver Code
public static void main(String []args){
int s = 2, t = 1, i;
int a[] = {-1, 2, 3, 4, 1};
int n = a.length ;
System.out.println(minimumMoves(n, a, s, t));
}
// This code is contributed by Ryuga
}
Python3
# Python3 implementation of the approach
# Function to return the number of moves
def minimumMoves(n, a, s, t):
x = s
for i in range(1, n+1):
# Destination reached
if x == t:
return i-1
x = a[x]
return -1
# Driver Code
if __name__ == "__main__":
s, t = 2, 1
a = [-1, 2, 3, 4, 1]
n = len(a)
print(minimumMoves(n, a, s, t))
# This code is contributed by Rituraj Jain
C#
// C# implementation of the approach
using System;
public class GFG{
// Function to return the number of moves
static int minimumMoves(int n, int []a, int s, int t)
{
int i, x;
x = s;
for (i = 1; i <= n; i++) {
if (x == t)
break;
x = a[x];
}
// Destination reached
if (x == t)
return i - 1;
else
return -1;
}
// Driver Code
public static void Main(){
int s = 2, t = 1;
int []a = {-1, 2, 3, 4, 1};
int n = a.Length ;
Console.WriteLine(minimumMoves(n, a, s, t));
}
// This code is contributed by inder_verma.
}
PHP
输出:
3