[AlgoExpert] Waterfall Streams

Waterfall Streams

  • Time : O(w * h)
  • Space : O(w)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <vector>

using namespace std;

vector<double> waterfallStreams(vector<vector<double>> array, int source) {
int n = array.size(), m = array[0].size();
vector<double> dp(m, 0.0);
dp[source] = 100.0;
for(int i = 0; i < n; i++) {
vector<double> nxt(m, 0.0);
double water = 0.0;
for(int j = 0; j < m; j++) {
if(i and array[i-1][j] == 1.0)
water = 0.0;
water += dp[j] / 2;
if(array[i][j] == 0.0) {
nxt[j] += water;
water = 0.0;
}
}
water = 0.0;
for(int j = m - 1; j >= 0; j--) {
if(i and array[i-1][j] == 1.0)
water = 0.0;
water += dp[j] / 2;
if(array[i][j] == 0.0) {
nxt[j] += water;
water = 0.0;
}
}
swap(nxt, dp);
}

return dp;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/waterfall-streams/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.