-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKnightsTour.cpp
42 lines (34 loc) · 1.09 KB
/
KnightsTour.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
#include <iostream>
#include <vector>
using namespace std;
bool isValid(vector<vector<int>> &grid, int r, int c, int n, int expVal)
{
if (r < 0 || c < 0 || r >= n || c >= n || grid[r][c] != expVal)
{
return false;
}
if (expVal == n * n - 1)
{
return true;
}
// 8 possible moves
int ans1 = isValid(grid, r - 2, c + 1, n, expVal + 1);
int ans2 = isValid(grid, r - 1, c + 2, n, expVal + 1);
int ans3 = isValid(grid, r + 1, c + 2, n, expVal + 1);
int ans4 = isValid(grid, r + 2, c + 1, n, expVal + 1);
int ans5 = isValid(grid, r + 2, c - 1, n, expVal + 1);
int ans6 = isValid(grid, r + 1, c - 2, n, expVal + 1);
int ans7 = isValid(grid, r - 1, c - 2, n, expVal + 1);
int ans8 = isValid(grid, r - 2, c - 1, n, expVal + 1);
return ans1 || ans2 || ans3 || ans4 || ans5 || ans6 || ans7 || ans8;
}
bool checkValidGrid(vector<vector<int>> &grid)
{
return isValid(grid, 0, 0, grid.size(), 0);
}
int main()
{
vector<vector<int>> grid = {{0, 3, 6}, {5, 8, 1}, {2, 7, 4}};
cout << checkValidGrid(grid) << endl;
return 0;
}