给出一个二维字符数组和一个单词,判断单词是否在数组中出现,
单词由相邻单元格的字母连接而成,相邻单元指的是上下左右相邻。同一单元格的字母不能多次使用。
例如:
给出的字符数组=
[↵ ["ABCE"],↵ ["SFCS"],↵ ["ADEE"]↵]
单词 ="ABCCED", -> 返回 true,
单词 ="SEE", ->返回 true,
单词 ="ABCB", -> 返回 false.
<?php
function exist($arrBoard, $word) {
$line = count($arrBoard);
$row = count($arrBoard[0]);
for ($i = 0; $i < $line; $i ++) {
for ($j = 0; $j < $row; $j ++) {
$ret = dfs($arrBoard, $i, $j, array(), $word, 0);
if ($ret) {
return true;
}
}
}
return false;
}
function dfs($arrBoard, $line, $row, $arrVisited, $word, $count) {
if ($count >= strlen($word)) {
return true;
}
if ($line < 0 || $line >= count($arrBoard) || $row < 0 || $row >= count($arrBoard[0])
|| $word[$count] != $arrBoard[$line][$row] || $arrVisited[$line][$row]) {
return false;
}
$arrVisited[$line][$row] = 1;
$dfs1 = dfs($arrBoard, $line + 1, $row, $arrVisited, $word, $count + 1);
$dfs2 = dfs($arrBoard, $line, $row + 1, $arrVisited, $word, $count + 1);
$dfs3 = dfs($arrBoard, $line - 1, $row, $arrVisited, $word, $count + 1);
$dfs4 = dfs($arrBoard, $line, $row - 1, $arrVisited, $word, $count + 1);
return $dfs1 || $dfs2 || $dfs3 || $dfs4;
}
$arr = [
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E'],
];
$word = 'ABCCED';
$word = 'SEE';
//$word = 'ABCB';
$ret = exist($arr, $word);
print intval($ret);