79. Word Search(js)

79. Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
题意:给定二维字符数组,是否存在邻接字符组成字符串
代码如下:
/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
//回溯
var exist = function(board, word) {
      var visited=[];
    for(var i=0;i<board.length;i++){
        visited[i]=new Array();
        for(var j=0;j<board[i].length;j++){
            visited[i][j]=false;
        }
    }
    for(var i=0;i<board.length;i++){
       
        for(var j=0;j<board[i].length;j++){
           
           if(word.charAt(0)===board[i][j] && backtrack(board,word,visited,i,j,0) ) return true;
        }
    }
    return false;
    
};
var backtrack=function(board,word,visited,i,j,index){
    if(word.length===index){
        return true;
    }
    if(i<0 || j<0 || i>=board.length || j>=board[0].length || board[i][j] !== word.charAt(index) || visited[i][j]){
        return false;
    }
    visited[i][j]=true;
    if(
        backtrack(board,word,visited,i+1,j,index+1) ||
        backtrack(board,word,visited,i-1,j,index+1) ||
        backtrack(board,word,visited,i,j+1,index+1) ||
        backtrack(board,word,visited,i,j-1,index+1))
        return true;
    visited[i][j]=false;
    return false;
    
}
原文地址:https://www.cnblogs.com/xingguozhiming/p/10568130.html