Paths in the offoffoffer matrix and the offoffer Matrix
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/c61c6999eecb4b8f88a98f66b273a3cc? Rp = 4 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Design a function to determine whether a path containing all characters of a string exists in a matrix. The path can start with any grid in the Matrix. Each step can move a grid to the left, right, up, and down of the matrix. If a path passes through a grid in the matrix, the path cannot enter the grid any more. For example, the B c e s f c s a d e matrix contains a "bccced" path, but the matrix does not contain the "abcb" path, because the first character B of the string occupies the second grid in the first row of the matrix, the path cannot enter the grid again.
Ideas
The basic questions of Deep Search Start with each grid and traverse them in four directions until the strings matching the question are found.
class Solution{public:bool hasPath(char* matrix, int rows, int cols, char* str){if(matrix==nullptr || rows<1 || cols<1 || str==nullptr)return false;bool *vis = new bool[rows*cols];memset(vis,false,rows*cols);int pathLength = 0;for(int i = 0; i<rows; ++i){for(int j = 0; j<cols; ++j){if(hasPathCore(matrix,rows,cols,i,j,str,pathLength,vis))return true;}}delete []vis;return false;}bool hasPathCore(char *matrix,int rows,int cols,int x,int y,char *str,int& pathLength,bool *vis){if(str[pathLength]=='\0')return true;bool hasPath = false;if(x>=0 && x<=rows && y>=0 && y<=cols && matrix[x*cols+y]==str[pathLength] && !vis[x*cols+y]){++pathLength;vis[x*cols+y] = true;hasPath = hasPathCore(matrix,rows,cols,x-1,y,str,pathLength,vis) ||hasPathCore(matrix,rows,cols,x+1,y,str,pathLength,vis) ||hasPathCore(matrix,rows,cols,x,y-1,str,pathLength,vis) ||hasPathCore(matrix,rows,cols,x,y+1,str,pathLength,vis);if(!hasPath){--pathLength;vis[x*cols+y] = false;}}return hasPath;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source