·  阅读 553

# 剑指 Offer 12. 矩阵中的路径

[["a","b","c","e"], ["s","f","c","s"], ["a","d","e","e"]]

``````示例 1：
输入：board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出：true

``````示例 2：
输入：board = [["a","b"],["c","d"]], word = "abcd"
输出：false

1 <= board.length <= 200

1 <= board[i].length <= 200

## 简单的来说 这道题就要用深度搜索来进行查找，先遍历整个数组找到第一个字符所在位置，然后对周围进行限制性递归查找，要记得还原现场

`````` /**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function(board, word) {
//先检测输入的数据是否为空
if(!board.length || !board[0].length || !word.length){
return false;
}
/**
* 遍历数组，找到最开头的word[0]
*/
for(var i=0;i<board.length;i++){
for(var j=0;j<board[0].length;j++){
if(board[i][j] == word[0]){
//查找周围的字符
if(findChar(board,i,j,word,1)){
return true;
}
//还原现场
board[i][j] = word[0];
}
}
}
return false;
};
//上下左右依次寻找字符
var findChar = function(board,x,y,word,n){
board[x][y] = 0;
var c = word[n];
if (n >= word.length){
return true;
}
if( x+1<board.length && c == board[x+1][y] ){
if(findChar(board,x+1,y,word,n+1)){
return true;
}
//退回时要还原现场
board[x+1][y] = c;
}
if( x-1 >= 0 && c == board[x-1][y] ){
if(findChar(board,x-1,y,word,n+1)){
return true;
}
board[x-1][y] = c;
}
if( y-1 >= 0 && c == board[x][y-1] ){
if(findChar(board,x,y-1,word,n+1)){
return true;
}
board[x][y-1] = c;
}
if(y+1 < board[0].length && c == board[x][y+1] ){
if(findChar(board,x,y+1,word,n+1)){
return true;
}
board[x][y+1] = c;
}
return false;
}