Wins the offer (PHP version rewritten) --- path matrix

? <PHP 
/ **
* PhpStorm the Created by.
* the User: FTX
* a Date: 2019/7/24
* Time: 11:18 AM
* /

// backtracking to find the path matrix

/ **
* @param $ the Matrix matrix array
$ rows @param number of rows *
* @param $ cols columns
* @param $ str looking string
* /
function hasPath (matrix $, $ rows, $ cols, STR $) {
IF (matrix == $ || $ rows null <$ cols. 1 || <|| $ STR. 1 == null) {
return to false;
}

$ visited = [$ * $ rows cols];
for ($ I = 0; $ I <COUNT ($ visited); $ I ++) {
$ visited [$ I] = 0;
}
for ($ Row = 0; $ Row <$ rows; $ Row ++) {
for ($ COL = 0; $ COL <$ cols ; ++ $ col) {
if (hasPathCore($matrix,$rows,$cols,$row,$col,$str,$visited)){
return true;
}
}
}

return 0;
}
//
function hasPathCore($matrix,$rows,$cols,$row,$col,$str,$visited)
{
if (count($str) <= 0) {
return true;
}

$hasPath = 0;
$index = $row * $cols + $col;
//
if ($row < 0 || $row >= $rows || $col < 0 || $col >= $cols || $matrix[$index] == false || $matrix[$index] != $str[0]) {
return false;
}
$visited[$index] = true;
$strRest = array_slice($str, 1);
if (hasPathCore($matrix, $rows, $cols, $row + 1, $col,$strRest, $visited) ||
hasPathCore($matrix, $rows, $cols, $row - 1, $col, $strRest,$visited) ||
hasPathCore($matrix, $rows, $cols, $row, $col + 1,$strRest, $visited) ||
hasPathCore($matrix, $rows, $cols, $row, $col - 1, $strRest,$visited)) {
$hasPath = 1;
} else {
$visited[$index] = false;
}

return $hasPath;
}
$matrix = ['A','B','C','E','S','F','C','S','A','D','E','F'];
$str = ['A','B','C','D'];
print_r(hasPath($matrix,3,4,$str));

Guess you like

Origin www.cnblogs.com/cyworz/p/11243095.html