Title Description
Please design a function to determine whether there is a path containing all characters of a string in a matrix. The path can start from any lattice in the matrix, and each step can move one lattice left, right, up and down in the matrix. If a path passes through a lattice in the matrix, it cannot enter the lattice again. For example, a 3 X 4 matrix such a s a b c e s f c s a d e e contains a path of the string "bcced", but the matrix does not contain a path of "abcb", because the path cannot enter the lattice again after the first character B of the string occupies the second lattice in the first row of the matrix.
link
Code
class Solution { public: bool hasPath(char* matrix, int rows, int cols, char* str) { bool flag = false; int **visited = (int**)malloc(sizeof(int*) * rows); for(int i = 0; i < rows; i++){ visited[i] = (int*)malloc(sizeof(int) * cols); } for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ for(int k = 0; k < rows; k++){ for(int t = 0; t < cols; t++){ visited[k][t] = 0; } } flag = flag || path(matrix, visited, rows, cols, i, j, str); } } return flag; } bool path(char* matrix, int** visited, int rows, int cols, int i, int j, char *str){ bool flag = false; if(matrix[i*cols+j] != str[0]){ return false; } else{ visited[i][j] = 1; if(str[1] == '\0'){ return true; } if(i - 1 >= 0 && visited[i-1][j] == 0){ // You can go up flag = flag || path(matrix, visited, rows, cols, i-1, j, str+1); } if(i + 1 <= rows-1 && visited[i+1][j] == 0){ // You can go down flag = flag || path(matrix, visited, rows, cols, i+1, j, str+1); } if(j - 1 >= 0 && visited[i][j-1] == 0){ // You can still go left flag = flag || path(matrix, visited, rows, cols, i, j-1, str+1); } if(j + 1 <= cols-1 && visited[i][j+1] == 0){ // You can also go right flag = flag || path(matrix, visited, rows, cols, i, j+1, str+1); } return flag; } } };