请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
回溯,格子的状态(未访问、已向上等),防撞(非未访问则回退)
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 class Solution {public : int _width; char _state[65535 ]{0 }; int xRoute[65535 ], yRoute[65535 ]; int x, y; inline char *state () { return &_state[y * _width + x]; } bool hasPath (char * matrix, int rows, int cols, char * str) { const int size = rows * cols; _width = cols; for (int startY = 0 ; startY < rows; startY++) { for (int startX = 0 ; startX < cols; startX++) { x = startX; y = startY; bool isFailed = false ; char *nextChar = str; while (!isFailed && *nextChar != '\0' ) { if (y >= 0 && y < rows && x >=0 && x < cols) { switch (*state()) { case 0 : if (matrix[y * _width + x] == *nextChar) { nextChar++; xRoute[nextChar - str] = x; yRoute[nextChar - str] = y; *state() = 1 ; y--; } else { if (nextChar == str) { isFailed = true ; } else { x = xRoute[nextChar - str]; y = yRoute[nextChar - str]; } } break ; case 1 : *state() = 2 ; x++; break ; case 2 : *state() = 3 ; y++; break ; case 3 : *state() = 4 ; x--; break ; case 4 : if (nextChar == str + 1 ) { isFailed = true ; *state() = 0 ; } else { nextChar--; *state() = 0 ; x = xRoute[nextChar - str]; y = yRoute[nextChar - str]; continue ; } break ; } if (*state() != 0 ) { x = xRoute[nextChar - str]; y = yRoute[nextChar - str]; } } else { x = xRoute[nextChar - str]; y = yRoute[nextChar - str]; } } if (isFailed) { continue ; } else { return true ; } } } return false ; } };