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.

For example,
Given board =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

思路:递归搜索,即递归搜索某一符合条件的字符的上、下、左、右四个方向,直到找到最后满足条件。

class Solution {
public:
    bool search(vector<vector<char> > &board,string &word,vector<vector<bool> > &visited,int i,int j,int index)
    {
        if(index==word.size())
            return true;
        //up
        if(i-1>=0 && board[i-1][j]==word[index] && visited[i-1][j]==false)
        {
            visited[i-1][j]=true;//已经访问
            if(search(board,word,visited,i-1,j,index+1))
                return true;
            visited[i-1][j]=false;
        }
        //down
        if(i+1<board.size() && board[i+1][j]==word[index] && visited[i+1][j]==false)
        {
            visited[i+1][j]=true;//已经访问
            if(search(board,word,visited,i+1,j,index+1))
                return true;
            visited[i+1][j]=false;
        }
        //left
        if(j-1>=0 && board[i][j-1]==word[index] && visited[i][j-1]==false)
        {
            visited[i][j-1]=true;//已经访问
            if(search(board,word,visited,i,j-1,index+1))
                return true;
            visited[i][j-1]=false;
        }
        //right
        if(j+1<board[0].size() && board[i][j+1]==word[index] && visited[i][j+1]==false)
        {
            visited[i][j+1]=true;//已经访问
            if(search(board,word,visited,i,j+1,index+1))
                return true;
            visited[i][j+1]=false;
        }
        return false;
    }
    bool exist(vector<vector<char> > &board, string word) {
        int n=board.size();
        if(n<0)
            return false;
        int m=board[0].size();
        for(int i=0;i<board.size();i++)
        {
            for(int j=0;j<m;j++)
            {
                if(board[i][j]==word[0])
                {
                    vector<vector<bool> >visited(n,vector<bool>(m,false));
                    visited[i][j]=true;
                    if(search(board,word,visited,i,j,1))
                        return true;
                }
            }
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/awy-blog/p/3813597.html