Number of different cyclic paths of length N in a tetrahedron
Last Updated :
13 Jan, 2023
Given a tetrahedron(vertex are A, B, C, D), the task is to find the number of different cyclic paths with length n from a vertex.
Note: Considering only a single vertex B i.e. to find the number of different cyclic paths of length N from B to itself.
Examples:
Input: 2
Output: 3
The paths of length 2 which starts and ends at D are:
B-A-B
B-D-B
B-C-B
Input: 3
Output: 6
Approach: Dynamic Programming can be used to keep track of the number of paths for previous values of N. Check for the number of moves which are left and where are we when we are moving in a path. That is 4n states, each with 3 options. Observe that all the vertices A, B, C are equivalent. Let zB be 1 initially and as at 0 steps, we can reach B itself only. Let zACD be 1 as paths for reaching other vertexes A, C and D is 0. Hence the recurrence relation formed will be:
Paths for N steps to reach b is = zADC*3
At every step, zADC gets multiplied by 2 (2 states) and it is added by zB since zB is the number of paths at step n-1 which comprises of the remaining 2 states.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int countPaths( int n)
{
int zB = 1;
int zADC = 0;
for ( int i = 1; i <= n; i++) {
int nzB = zADC * 3;
int nzADC = (zADC * 2 + zB);
zB = nzB;
zADC = nzADC;
}
return zB;
}
int main()
{
int n = 3;
cout << countPaths(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int countPaths( int n)
{
int zB = 1 ;
int zADC = 0 ;
for ( int i = 1 ; i <= n; i++)
{
int nzB = zADC * 3 ;
int nzADC = (zADC * 2 + zB);
zB = nzB;
zADC = nzADC;
}
return zB;
}
public static void main (String[] args)
{
int n = 3 ;
System.out.println(countPaths(n));
}
}
|
Python3
def countPaths(n):
zB = 1
zADC = 0
for i in range ( 1 , n + 1 ):
nzB = zADC * 3
nzADC = (zADC * 2 + zB)
zB = nzB
zADC = nzADC
return zB
n = 3
print (countPaths(n))
|
C#
using System;
class GFG{
static int countPaths( int n)
{
int zB = 1;
int zADC = 0;
for ( int i = 1; i <= n; i++)
{
int nzB = zADC * 3;
int nzADC = (zADC * 2 + zB);
zB = nzB;
zADC = nzADC;
}
return zB;
}
static public void Main ()
{
int n = 3;
Console.WriteLine(countPaths(n));
}
}
|
PHP
<?php
function countPaths( $n )
{
$zB = 1;
$zADC = 0;
for ( $i = 1; $i <= $n ; $i ++)
{
$nzB = $zADC * 3;
$nzADC = ( $zADC * 2 + $zB );
$zB = $nzB ;
$zADC = $nzADC ;
}
return $zB ;
}
$n = 3;
echo countPaths( $n );
?>
|
Javascript
<script>
function countPaths(n)
{
let zB = 1;
let zADC = 0;
for (let i = 1; i <= n; i++)
{
let nzB = zADC * 3;
let nzADC = (zADC * 2 + zB);
zB = nzB;
zADC = nzADC;
}
return zB;
}
let n = 3;
document.write(countPaths(n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...