forked from windynight/InterviewPuzzle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCouldYouGoThroughTheRiver.cpp
More file actions
73 lines (63 loc) · 1.5 KB
/
Copy pathCouldYouGoThroughTheRiver.cpp
File metadata and controls
73 lines (63 loc) · 1.5 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
*
* Question:
* There is a river, "** *** ** **** * * ***", '*' star stands for rock, ' ' space stands for water.
* You are at the position 0 in speed 0 in the beginning, every time you could increase your current speed
* by 1 or decreasing it by 1 or keep it as the same. But speed should be non negtive.
* Could you reach the end of the river?
*
*
* Solution:
* Memorization Dynamic Programming.
* Search each state of dp[p][s], which should be true if we could reach position p with speed s, otherwise,
* false.
* Time and space complexity are both: O(n*sqrt(n))
*
*/
#include <iostream>
#include <vector>
using namespace std;
int a[1000], N;
string river;
const int LEN = 100;
int f[LEN][LEN];
int caled[LEN][LEN];
bool reachable(int posi, int speed)
{
if (posi == N - 1 && river[posi] == '*') {
return true;
} else if (posi >= N || river[posi] == ' ') {
return false;
} else if (caled[posi][speed]) {
return f[posi][speed];
}
f[posi][speed] = false;
caled[posi][speed] = true;
for (int i = -1; i <= 1; i ++) {
int s = speed + i;
if (s > 0) {
f[posi][speed] |= reachable(posi + s, s);
if (f[posi][speed]) {
return true;
}
}
}
return f[posi][speed];
}
bool isReachable()
{
memset(caled, false, sizeof(caled));
return reachable(0, 0);
}
int main()
{
while (getline(cin, river)) {
N = river.length();
if (isReachable()) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}