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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #include <vector> #include <iostream>
struct Matrix { Matrix(int rows, int cols): m_rows(rows), m_flags(rows) { for(auto& row: m_rows) { row.resize(cols); }
for(auto& row: m_flags) { row.resize(cols); } }
bool find(const char *target, int& row, int& col) {
for (auto i = 0; i < m_rows.size(); ++i) { for (auto j = 0; j < m_rows[i].size(); ++j) { if (m_rows[i][j] == *target) { m_flags[i][j] = true; if (check(target, i, j)) { row = i; col = j; return true; } m_flags[i][j] = false; } } }
return false; }
bool check(const char *target, int row, int col) {
if (target and *target != '\0' and target[1] != '\0') {
if (0 < row and not m_flags[row - 1][col] and m_rows[row - 1][col] == target[1]) { m_flags[row - 1][col] = true; if (check(target + 1, row - 1, col)) { return true; } m_flags[row - 1][col] = false; }
if (0 < col and not m_flags[row][col - 1] and m_rows[row][col - 1] == target[1]) { m_flags[row][col - 1] = true; if (check(target + 1, row, col - 1)) { return true; } m_flags[row][col - 1] = false; }
if (row < m_rows.size() - 1 and not m_flags[row + 1][col] and m_rows[row + 1][col] == target[1]) { m_flags[row + 1][col] = true; if (check(target + 1, row + 1, col)) { return true; } m_flags[row + 1][col] = false; }
if (col < m_rows[row].size() - 1 and not m_flags[row][col + 1] and m_rows[row][col + 1] == target[1]) { m_flags[row ][col + 1] = true; if (check(target + 1, row, col + 1)) { return true; } m_flags[row][col + 1] = false; }
return false;
} return true; }
template<typename InputStream> InputStream& input(InputStream& in) {
for(auto i = 0; i < m_rows.size(); ++i) { std::string line; in >> line; m_rows[i].assign(line.begin(), line.end()); }
return in; }
private: std::vector<std::vector<char>> m_rows; std::vector<std::vector<bool>> m_flags; };
template<typename InputStream> InputStream& operator>>(InputStream& in, Matrix& m) { return m.input(in); }
int main() {
int row, col; std::string target;
std::cin >> row >> col >> target;
Matrix m(row, col);
std::cin >> m;
if (m.find(target.c_str(), row, col)) { std::cout << row + 1 << ' ' << col + 1 << std::endl; } else { std::cout << "NO" << std::endl; }
return 0; }
|