12- prove safety offer- face questions matrix Path - backtracking

/ * 
Title: 
	Design of a function, determining whether there is a route that contains all the characters in the string in a matrix. 
	A path can begin in any cell strings, each step of the up, down, left and right movement of a grid. 
	If one path after a grid matrix, then the path can not pass through the cell again. 
* / 
/ * 
Idea: 
	using backtracking. 
	Through the array, which when elected in a grid, if the current position matches the specified string, 
	then it detects the surrounding lattice match, if match, continue in-depth, do not match, a fallback grid. 
	
* / 

#Include <the iostream> 
#include <Vector> 
#include <string.h> 
the using namespace STD; 


BOOL hasPathCore (Matrix const char *, int rows, int cols, Row int, int COL, STR const char *, int & lengthAt , BOOL * visited) { 
    IF (STR [lengthAt] == '\ 0') return to true; 
    ! IF (Row> = 0 && COL> = 0 && Row <rows && COL <cols && visited [cols * Row + COL ] &&
        cout<<" "<<matrix[row*cols+col];
        if(hasPathCore(matrix,rows,cols,row+1,col,str,lengthAt,visited) || hasPathCore(matrix,rows,cols,row-1,col,str,lengthAt,visited) ||
           hasPathCore(matrix,rows,cols,row,col+1,str,lengthAt,visited) || hasPathCore(matrix,rows,cols,row,col-1,str,lengthAt,visited) ) {
            return true;
           }
        --lengthAt;
        visited[row*cols+col] = false;
    }

    return false;
}
bool hasPath(char* matrix,int rows,int cols,char* str){
    if(!matrix || rows <= 0 || cols <= 0 || !str){
        return false;
    }
    bool* visited = new bool[rows*cols];
    memset(visited,0,rows*cols);
    int lengthAt = 0;
    for(int row = 0; row < rows; row++){
        for(int col = 0; col < cols; col++){
            cout<<row<<" "<<col<<endl;
            cout<<matrix[cols*row + col]<<" ";
            if(hasPathCore(matrix,rows,cols,row,col,str,lengthAt,visited)){

                return true;
            }
            cout<<endl;
        }
    }
    return false;
}



int main()
{
    char matrix[] = "ABCEHJIG SFCSLOPQ ADEEMNOE ADIDEJFM VCEIFGGS";
    //char* matrix = "abtgcfcsjdeh";
    char str[] = "SGGFIECVAASABCEHJIGQEM";
    cout<<hasPath(matrix,5,8,str);
    return 0;
}

   

Guess you like

Origin www.cnblogs.com/buaaZhhx/p/11838785.html