面試題12:矩陣中的路徑
阿新 • • 發佈:2018-12-22
題目:設計一個函式,判斷矩陣中是否存在一條包含某字串的所有路徑
問題描述:路徑可以從矩陣的任意一格開始,每一步可以在矩陣中,向上,下,左,右移動一格,如果一條路經過了矩陣的某一格,那麼不能再次訪問這個格子
列如:矩陣abcdefghi含有字串abefg
程式碼如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//是否經過這個格子 bool hasPathCore(const char* matrix,int rows,int cols,int row,int col,const char* str,int& pathLength,bool* visited) { if(str[pathLength]=='\0') //判斷字串是否遍歷結束 return true; bool hasPath=false; //判斷這個格子合法即未訪問並且和字串中的字元一樣 if(row>=0&&row<rows&&col>=0&&col<cols&&matrix[row*cols+col]==str[pathLength]&&!visited[row*cols+col]) { ++pathLength;//路徑長度加一 visited[row*cols+col]=true;//將這個格子置為已訪問 //上下左右遍歷矩陣中是否有和字串中下一個字元一樣的字元 hasPath=hasPathCore(matrix,rows,cols,row,col-1,str,pathLength,visited) ||hasPathCore(matrix,rows,cols,row-1,col,str,pathLength,visited) ||hasPathCore(matrix,rows,cols,row,col+1,str,pathLength,visited) ||hasPathCore(matrix,rows,cols,row+1,col,str,pathLength,visited); //沒有路徑可走 if(!hasPath) { //回溯法回到上一個格子 --pathLength;//將回到上一個格子 visited[row*cols+col]=false;//將這個格子置為未訪問 } } return hasPath; } //判斷是否有一條路徑 bool hasPath(char* matrix,int rows,int cols,char* str) //矩陣,行數,列數,待查詢字串路徑 { if(matrix==nullptr||rows<1||cols<1||str==nullptr)//判斷數組合法 return false; bool *visited=new bool[rows*cols]; //矩陣是否走過 memset(visited,0,rows*cols); //初始化為0 int pathLength=0; //初始化路徑長度為0 for(int row=0;row<rows;++row) { for(int col=0;col<cols;++col) { if(hasPathCore(matrix,rows,cols,row,col,str,pathLength,visited)) { return true; } } } delete[] visited; return false; } //測試程式碼: void Test(char* testName,char* matrix,int rows,int cols,char* str) { if(testName!=NULL) printf("%s begins:",testName); if(hasPath(matrix,rows,cols,str)==true) printf("HasPath.\n"); else printf("NoPath.\n"); } void Test1() { char* str="abefi"; char matrix[]={"abcdefghi"}; Test("Test1",(char*)matrix,3,3,str); } void Test2() { char* str="abefg"; char matrix[]={"abcdefghi"}; Test("Test2",(char*)matrix,3,3,str); } int main() { Test1(); Test2(); return 0; }