LeetCode #79

来源:互联网 发布:手机翻页电子书软件 编辑:程序博客网 时间:2024/05/02 12:56

题目描述:

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 =

[  ['A','B','C','E'],  ['S','F','C','S'],  ['A','D','E','E']]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

字符每次延伸都可以往相邻的四个方向,所以可以用递归分别搜索当前字符的四个方向,只要有一个方向可行就可以,但是要注意访问过的字符需要进行标记,之后就不能访问之前已经访问过的字符。

class Solution {public:    bool exist(vector<vector<char>>& board, string word) {        if(word.empty()) return true;        else if(board.empty()) return false;        else if(board[0].empty()) return false;        for(int i=0;i<board.size();i++)        {            for(int j=0;j<board[0].size();j++)            {                if(board[i][j]==word[0]&&searchSurround(board,word,i,j,0))                     return true;            }        }        return false;    }        bool searchSurround(vector<vector<char>> board,string word,int i,int j,int start)    {        if(board[i][j]!=word[start]) return false;        else if(board[i][j]==word[start]&&start==(word.size()-1)) return true;        else if(board[i][j]==word[start]&&start<(word.size()-1))        {            bool result=false;            board[i][j]='0';            if(i>0&&board[i-1][j]!='0')                 result=result||searchSurround(board,word,i-1,j,start+1);            if(i<(board.size()-1)&&board[i+1][j]!='0')                 result=result||searchSurround(board,word,i+1,j,start+1);            if(j>0&&board[i][j-1]!='0')                 result=result||searchSurround(board,word,i,j-1,start+1);            if(j<(board[0].size()-1)&&board[i][j+1]!='0')                 result=result||searchSurround(board,word,i,j+1,start+1);            return result;        }    }};