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
| #include<iostream> using namespace std;
bool hasPathCore(const char* matirix,int rows,int cols, int row,int col, const char* str,int& pathLength,bool* visited) { if (str[pathLength] == '\0') { return true; }
bool haspath = 0; if (row >= 0 && row < rows && col >= 0 && col < cols && matirix[row * cols + col ]== str[pathLength] && !visited[row * cols + col]) { pathLength++; visited[row * col + col] = 1;
haspath = hasPathCore(matirix, rows, cols, row, col - 1, str, pathLength, visited) || hasPathCore(matirix, rows, cols, row - 1, col, str, pathLength, visited) || hasPathCore(matirix, rows, cols, row, col + 1, str, pathLength, visited) || hasPathCore(matirix, rows, cols, row + 1, col, str, pathLength, visited); if (!haspath) { --pathLength; visited[row * cols * +col] = 0; } } return haspath; }
bool hasPath(const char* matirix,int rows,int cols,const char* str) { if (!matirix || rows <= 0 || cols <= 0 || !str) { return false; } bool* visited = new bool[cols * rows]; memset(visited, 0, cols * rows);
int pathLength = 0;
for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { if (hasPathCore(matirix, rows,cols, row, col, str, pathLength, visited)) { return true; } } } delete[] visited; return false; }
void Test(const char* TestTitle, const char* dest,const char* str,int rows, int cols, bool HopeResult) { cout << "预计结果为" << HopeResult << " "; if (hasPath(dest, rows, cols, str) == HopeResult) { cout << TestTitle << "与预计结果相同" << endl; } else { cout << TestTitle << "与预计结果不同" << endl; } } int main(void) {
const char* TestTitle = "测试1"; const char* dest = "ABTGCFCSJDEH"; const char* str = "BFCEH"; Test(TestTitle, dest, str, 3, 4, 1); return 0; }
|