C/C++面试题—矩阵中的路径【回溯法应用】
生活随笔
收集整理的這篇文章主要介紹了
C/C++面试题—矩阵中的路径【回溯法应用】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。
例如 a b c e s f c s a d e e 矩陣中包含一條字符串”bcced”的路徑,但是矩陣中不包含”abcb”路徑,因為字符串的第一個字符b占據了矩陣中的第一行第二個格子之后,路徑不能再次進入該格子。
解題思路
和馬踏棋盤的思路一樣,都是采用回溯法。如果走到某一個結點,繼續從這個節點出發,如果走到頭了,就回溯到該結點,從這個節點的其他結點再次嘗試。
解題代碼
#include <iostream> using namespace std; /* 題目描述:請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。 路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。 如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如 a b c e s f c s a d e e 矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑, 因為字符串的第一個字符b占據了矩陣中的第一行第二個格子之后,路徑不能再次進入該格子。*/ class SolutionHasPath { public:bool hasPath(char* matrix, int rows, int cols, char* str){if (nullptr == matrix || rows <= 0 || cols <= 0 || nullptr == str)return false;bool *visited = new bool[rows*cols]{ false };int pathLen = 0;bool result = false;for (int row = 0; row < rows; row++){for (int col = 0; col < cols; col++){result = hasPathCore(matrix, row, rows, col, cols, str, pathLen, visited);if (result) //找一條路break;}}delete[] visited;return result;}bool hasPathCore(char* matrix, int row, int rows,int col, int cols, char* str, int &pathLen,bool *visited){if (str[pathLen] == '\0')return true;bool isPathNode = false;if (row >= 0 && row < rows && col >= 0 && col < cols&& str[pathLen] == matrix[row*cols + col] && !visited[row*cols + col]) //和當前節點匹配,繼續往下走{pathLen++;visited[row*cols + col] = true;isPathNode = hasPathCore(matrix, row-1, rows, col, cols, str, pathLen, visited) || hasPathCore(matrix, row+1, rows, col, cols, str, pathLen, visited)|| hasPathCore(matrix, row, rows, col-1, cols, str, pathLen, visited)|| hasPathCore(matrix, row, rows, col+1, cols, str, pathLen, visited);if (!isPathNode) //沒有一條路行的通,回溯{pathLen--;visited[row*cols + col] = false;}}return isPathNode;}};int main(int argc, char *argv[]) {SolutionHasPath Path;//"ABCESFCSADEE", 3, 4, "SEE"char matrix[] = {'A','B','C','E','S','F','C','S','A','D','E','E'};char *str = "SEE";bool result = Path.hasPath(matrix,3,4,str);cout << "有沒有路徑:" << result << endl;return 0; }運行測試
總結
以上是生活随笔為你收集整理的C/C++面试题—矩阵中的路径【回溯法应用】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: shell 字符串分割(简单)
- 下一篇: 华为云ModelArts