Title Description
Please design a function to determine if there is a path in a matrix that contains all characters of a string. The path can start from any grid in the matrix, and each step can move to the left, right, up, and down a grid in the matrix. If a path passes through a lattice in the matrix, the path can no longer enter the grid. For example a B c e s f C s a D-e matrix contains a path to the string "bcced", but the matrix does not contain a "ABCB" path, because the first character B of the string occupies the second lattice in the first row of the matrix, and the path cannot enter the lattice again.
Code:
/** uses a state array to save previously accessed characters, then press up, down, left, and right recursively */public class solution {public boolean haspath (char[] matrix, int rows, int cols, Char[] str) {int flag[] = new Int[matrix.length]; for (int i = 0; i < rows; i++) {for (int j = 0; J < cols; J + +) {if (For helper (matrix, rows, Cols, I, J, str, 0, flag) return true; }} return false; } Private Boolean helper (char[] matrix, int rows, int cols, int i, Int j, char[] str, int k, int[] flag) {int index = i * cols + j; if (I < 0 | | I >= rows | | J < 0 | | J >= cols | | matrix[index]! = Str[k] | | flag[index] = = 1) return False if (k = = str.length-1) return true; Flag[index] = 1; if (helper (matrix, rows, cols, I-1, J, str, K + 1, flag) | | Helper (Matrix, rows, cols, i + 1, j, str, k + 1, flag) | | Helper (matrix, rows, cols, I, j-1, str, k + 1, flag) | | HelpeR (Matrix, rows, cols, I, j + 1, str, k + 1, flag)) {return true; } Flag[index] = 0; return false; }}
The path in the matrix of the offer (65) of the sword