[LeetCode] Word Search

来源:互联网 发布:php设计模式视频教程 编辑:程序博客网 时间:2024/03/29 20:16

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 exist(vector<vector<char> > &board, string word) {        // Start typing your C/C++ solution below        // DO NOT write int main() function                int m=board.size();    if (m==0||word.empty())    return word.empty();    int n=board[0].size();    for(int i=0;i<m;i++)    assert(board[i].size()==n);    for(int i=0;i<m;i++)    for(int j=0;j<n;j++)    {    if ( board[i][j]==word[0]&&solve(i,j,board,word,0) )    return true;    }    return false;    }    bool solve(int x,int y, vector<vector<char> >& board,string& word,int k)    {    int m=board.size();    int n=board[0].size();    int len=word.length();    if ( k==len )    return true;    if ( x<0||x>=m||y<0||y>=n)    return false;    if ( board[x][y]!=word[k])    return false;        board[x][y]='#';    if ( solve(x-1,y,board,word,k+1)||solve(x+1,y,board,word,k+1)|| solve(x,y-1,board,word,k+1) || solve(x,y+1,board,word,k+1))    return true;    board[x][y]=word[k];    return false;    }};