|
| 1 | +#include <vector> |
| 2 | +#include <iostream> |
| 3 | +#include <algorithm> |
| 4 | + |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +class Solution { |
| 8 | + public: |
| 9 | + bool checkValidGrid(vector<vector<int>>& grid) { |
| 10 | + struct helper { |
| 11 | + int r = 0; |
| 12 | + int c = 0; |
| 13 | + int step = 0; |
| 14 | + bool operator<(const helper& b) { return this->step < b.step; } |
| 15 | + }; |
| 16 | + |
| 17 | + vector<helper> arr; |
| 18 | + int m = grid.size(), n = grid[0].size(); |
| 19 | + |
| 20 | + if (grid[0][0] != 0) return false; |
| 21 | + |
| 22 | + for (auto i = 0; i < m; ++i) |
| 23 | + for (auto j = 0; j < n; ++j) { |
| 24 | + arr.push_back({i, j, grid[i][j]}); |
| 25 | + } |
| 26 | + |
| 27 | + sort(arr.begin(), arr.end()); |
| 28 | + |
| 29 | + vector<pair<int, int>> valid = {{1, 2}, {1, -2}, {-1, -2}, {-1, 2}, |
| 30 | + {2, 1}, {2, -1}, {-2, -1}, {-2, 1}}; |
| 31 | + |
| 32 | + for (int i = 1; i < m * n; ++i) { |
| 33 | + bool found = false; |
| 34 | + for (auto v : valid) { |
| 35 | + if (v.first == (arr[i].r - arr[i - 1].r) && |
| 36 | + v.second == (arr[i].c - arr[i - 1].c)) { |
| 37 | + found = true; |
| 38 | + break; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + if (found == false) return false; |
| 43 | + } |
| 44 | + |
| 45 | + return true; |
| 46 | + } |
| 47 | +}; |
| 48 | + |
| 49 | +int main(int argc, char const* argv[]) { |
| 50 | + Solution s; |
| 51 | + // vector<vector<int>> v = {{0, 11, 16, 5, 20}, |
| 52 | + // {17, 4, 19, 10, 15}, |
| 53 | + // {12, 1, 8, 21, 6}, |
| 54 | + // {3, 18, 23, 14, 9}, |
| 55 | + // {24, 13, 2, 7, 22}}; |
| 56 | + |
| 57 | + vector<vector<int>> v = {{24, 11, 22, 17, 4}, |
| 58 | + {21, 16, 5, 12, 9}, |
| 59 | + {6, 23, 10, 3, 18}, |
| 60 | + {15, 20, 1, 8, 13}, |
| 61 | + {0, 7, 14, 19, 2}}; |
| 62 | + cout << s.checkValidGrid(v) << endl; |
| 63 | + return 0; |
| 64 | +} |
0 commit comments