-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.cpp
79 lines (73 loc) · 2.33 KB
/
Solution.cpp
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
74
75
76
77
78
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <deque>
#include <unordered_map>
#include <cmath>
#include <queue>
using namespace std;
enum From {up, down, _left, _right} ;
class Solution {
public:
int m;
int n;
bool go(vector<vector<int>>& grid, int i, int j, From from) {
if (i < 0 or i >= m or j < 0 or j >= n) return false;
if (i == 0 and j == 0) // loop
return false;
bool isfinal =( i + 1 == m and j + 1 == n );
switch (grid[i][j]) {
case 1:
if (from == _left) return go (grid, i, j+1, _left) or isfinal;
if (from == _right) return go(grid, i, j-1, _right) or isfinal;
break;
case 2:
if (from == up) return go (grid, i+1, j, up) or isfinal;
if (from == down) return go(grid, i-1, j, down) or isfinal;
break;
case 3:
if (from == _left) return go (grid, i+1, j, up) or isfinal;
if (from == down) return go(grid, i, j-1, _right) or isfinal;
break;
case 4:
if (from == _right) return go (grid, i+1, j, up) or isfinal;
if (from == down) return go(grid, i, j+1, _left) or isfinal;
break;
case 5:
if (from == _left) return go (grid, i-1, j, down) or isfinal;
if (from == up) return go(grid, i, j-1, _right) or isfinal;
break;
case 6:
if (from == up) return go (grid, i, j+1, _left) or isfinal;
if (from == _right) return go(grid, i-1, j, down) or isfinal;
break;
}
return false;
}
// dfs
bool hasValidPath(vector<vector<int>>& grid) {
m = grid.size();
n = grid[0].size();
if (m == 1 and n == 1) return true;
switch (grid[0][0]) {
case 2:
case 3:
return go(grid, 1, 0, up);
case 5:
return false;
case 1:
case 6:
return go(grid, 0, 1, _left);
case 4:
return go(grid, 0, 1, _left) or go(grid, 1, 0, up);
}
return false;
}
};
int main() {
Solution a;
return 0;
}