-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathPuzzle.cpp
More file actions
59 lines (52 loc) · 1.49 KB
/
pathPuzzle.cpp
File metadata and controls
59 lines (52 loc) · 1.49 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
#include <iostream>
#include <functional>
#include <vector>
#include <numeric>
using namespace std;
class Solution {
private:
int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };
public:
vector<int> pathPuzzle(int col[], int row[], int n) {
vector<vector<bool>> vis(n, vector<bool>(n, false));
vector<int> path;
function<bool(int, int)> dfs = [&](int x, int y) -> bool {
if (x < 0 || x >= n || y < 0 || y >= n) return false;
if (vis[x][y]) return false;
if (row[x] == 0 || col[y] == 0) return false;
row[x]--;
col[y]--;
vis[x][y] = true;
path.push_back(x * n + y);
if (x == n - 1 && y == n - 1 &&
accumulate(row, row + n, 0) == 0 &&
accumulate(col, col + n, 0) == 0) return true;
for (int d = 0; d < 4; d++) {
if (dfs(x + dx[d], y + dy[d])) return true;
}
row[x]++;
col[y]++;
vis[x][y] = false;
path.pop_back();
return false;
};
dfs(0, 0);
return path;
};
};
int main()
{
int n;
cin >> n;
int* row = new int[n], * col = new int[n];
Solution s;
for (int i = 0; i < n; i++) cin >> col[i];
for (int i = 0; i < n; i++) cin >> row[i];
vector<int> path = s.pathPuzzle(col, row, n);
for (auto p : path) cout << p << ' ';
cout << endl;
delete [] row;
delete [] col;
return 0;
}