生活随笔
收集整理的這篇文章主要介紹了
Q12矩阵中的路径 回溯法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
回朔法
文章目錄
矩陣中的路徑
題目
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如 [abcesfcsadee]\begin{bmatrix} a & b & c &e \\ s & f & c & s \\ a & d & e& e\\ \end{bmatrix}\quad ? ? ? a s a ? b f d ? c c e ? e s e ? ? ? ?
矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字符串的第一個字符b占據了矩陣中的第一行第二個格子之后,路徑不能再次進入該格子。
思路
回溯法
實現
記得寫visistMtx的釋放語句,delete 進行下一個判斷錢,將visit置true,如果不匹配,重新置回false。
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 * visitMatrix
= new bool [ rows
* cols
] ; memset ( visitMatrix
, false , rows
* cols
) ; for ( int r
= 0 ; r
< rows
; ++ r
) { for ( int c
= 0 ; c
< cols
; ++ c
) { int pathLen
= 0 ; if ( hasPathCore ( matrix
, rows
, cols
, str
, pathLen
, visitMatrix
, r
, c
) ) return true ; } } delete [ ] visitMatrix
; return false ; } bool hasPathCore ( char * matrix
, int rows
, int cols
, char * str
, int pathLen
, bool * visitMtx
, int r
, int c
) { char tag
= str
[ pathLen
] ; if ( tag
== '\0' ) return true ; ++ pathLen
; bool hasMatch
= false ; if ( r
< rows
&& r
>= 0 && c
< cols
&& c
>= 0 && ! visitMtx
[ r
* cols
+ c
] && matrix
[ r
* cols
+ c
] == tag
) { visitMtx
[ r
* cols
+ c
] = true ; hasMatch
= hasPathCore ( matrix
, rows
, cols
, str
, pathLen
, visitMtx
, r
+ 1 , c
) || hasPathCore ( matrix
, rows
, cols
, str
, pathLen
, visitMtx
, r
- 1 , c
) || hasPathCore ( matrix
, rows
, cols
, str
, pathLen
, visitMtx
, r
, c
+ 1 ) || hasPathCore ( matrix
, rows
, cols
, str
, pathLen
, visitMtx
, r
, c
- 1 ) ; if ( ! hasMatch
) visitMtx
[ r
* cols
+ c
] = false ; } return hasMatch
; }
} ;
總結
以上是生活随笔 為你收集整理的Q12矩阵中的路径 回溯法 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。