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.

For example,
Given board =

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

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

这也算是设置标志位的经典例子了吧。(回溯)

class Solution {
public:
    bool isExist(vector<vector<char>>& board,string wordsub,int h,int w, vector<vector<bool>>&flag)
    {
        int direct[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
        for(int d=0;d<4;d++)
        {
            int jj=h+direct[d][0];
            int ii=w+direct[d][1];
            if(jj>=0&&jj<board.size()&&ii>=0&&ii<board[0].size())
            {
                if(wordsub[0]==board[jj][ii]&&flag[jj][ii]==0)
                {
                    flag[jj][ii]=1;
                    if(wordsub.size()==1||isExist(board,wordsub.substr(1),jj,ii,flag))
                        return true;
                    flag[jj][ii]=0;
                }
                
            }
                
        }
        return false;
    }
   
    bool exist(vector<vector<char>>& board, string word) {
        int length=word.size();
        int Height=board.size();
        int Width=board[0].size();
        vector<vector<bool>> flag(Height,vector<bool>(Width,0));
        for(int h=0;h<Height;h++)
            for(int w=0;w<Width;w++)
            {
                if(board[h][w]==word[0])
                {
                    flag[h][w]=1;
                    if( word.size()==1||isExist(board,word.substr(1),h,w,flag))
                        return true;
                    flag[h][w]=0;
                }
            }
        return false;
    }
};

 

posted @ 2015-05-25 21:39  linqiaozhou  阅读(368)  评论(0编辑  收藏  举报