[AlgoExpert] Number Of Ways To Traverse Graph

Number Of Ways To Traverse Graph

  • Time : O(wh)
  • Space : O(min(w, h))
1
2
3
4
5
6
7
8
9
10
11
12
13
using namespace std;

int numberOfWaysToTraverseGraph(int width, int height) {
if(width > height) return numberOfWaysToTraverseGraph(height, width);
vector<int> dp(width, 1);
for(int i = 1; i < height; i++) {
for(int j = 1; j < width; j++) {
dp[j] += dp[j-1];
}
}
return dp.back();
}

  • Time : O(w + h)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using namespace std;

int fact(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
return n * fact(n - 1);
}

int numberOfWaysToTraverseGraph(int width, int height) { // nCr concepts
if(height == 1 or width == 1) return 1;
int n = width - 1 + height - 1;
int r = min(width - 1, height - 1);
return (int)(fact(n) / (fact(r) * fact(n-r)));
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/AlgoExpert/number-of-ways-to-traverse-graph/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.