又是一道回溯法的问题。目前关于回溯法,只是处于能看懂代码的阶段。给你一道新题,估计还是很难答得出来,不过没关系。先把这几道题弄熟了再说。
bool HasPathCore(char* matrix, int rows, int columns, int row, int col, char* str, int &length, bool* visited) { if (str[length] == ‘\0‘) return true; bool HasPath = false; if (row < rows&&row >= 0 && col >= 0 && col < columns&&matrix[row*columns + col] == str[length] && visited[row*columns + col] == false) { ++length; visited[row*columns + col] = true; HasPath = HasPathCore(matrix, rows, columns, row, col - 1, str, length, visited) || HasPathCore(matrix, rows, columns, row, col + 1, str, length, visited) || HasPathCore(matrix, rows, columns, row - 1, col, str, length, visited) || HasPathCore(matrix, rows, columns, row + 1, col, str, length, visited); if (!HasPath) { --length; visited[row*columns + col] = false; } } return HasPath; }
//确定图中是否有可以使用的路径 bool HasPath(char* matrix, int rows, int columns, char* str) { if (matrix == NULL || rows <= 0 || columns <= 0 || str == NULL) return false; bool *visited = new bool[rows*columns]; memset(visited, 0, rows*columns); int PathLength = 0; for (int col = 0; col < columns; col++) { for (int row < 0; row < rows; ++row) { if (HasPathCore(matrix, rows, columns, row, col, str, PathLength, visited)) return true; } } delete[] visited; return false; }
时间: 2024-11-09 13:22:16