Word Search

来源:互联网 发布:java 对象转map 编辑:程序博客网 时间:2024/05/16 05:55
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.

思路:

对于board的每一个元素进行DFS,主要对已经访问过的记录做好标记即可

class Solution {public:    bool exist(vector<vector<char>>& board, string word) {        //条件判断        if(word.size()==0)            return true;        if(board.size()==0)            return false;        bool res=false;        vector<vector<bool> >visited(board.size(),vector<bool>(board[0].size(),false));        for(int i=0;i<board.size();i++)            for(int j=0;j<board[i].size();j++)            {                if(search_word(board,word,i,j,visited,0))                {                    res=true;                    break;                }            }        return res;    }    //DFS判断搜索问题    bool search_word(vector<vector<char>>&board,string word,int i,int j,vector<vector<bool>>&visited,int index)    {        if(index==word.size())            return true;        if(i<0||j<0||i>=board.size()||j>=board[0].size()||visited[i][j]||board[i][j]!=word[index])            return false;        visited[i][j]=true;        bool tmpres=search_word(board,word,i+1,j,visited,index+1)            ||search_word(board,word,i-1,j,visited,index+1)            ||search_word(board,word,i,j+1,visited,index+1)            ||search_word(board,word,i,j-1,visited,index+1);        visited[i][j]=false;        return tmpres;    }        };


0 0
原创粉丝点击