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 =

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

解答:用回溯,并用一个矩阵标记每个走过的位置,若后退的话,要把当前位置置false。

class Solution {
public:
    bool search_tag(vector<vector<char>>& board, vector<vector<bool>>& cur, string s, int beg, int r, int l){
    int rows = board.size();
    int cols = board[0].size();
    int lens = s.size();
    if(s[beg] == board[r][l]){
        cur[r][l]=true;
        if(beg+1 == lens)
            return true;
        if(r-1>=0 && !cur[r-1][l])
            if (search_tag(board,cur,s, beg+1, r-1, l)) return true;
        if(r+1<rows && !cur[r+1][l])
            if (search_tag(board,cur, s, beg+1, r+1, l)) return true;
        if(l-1>=0 && !cur[r][l-1])
            if (search_tag(board,cur, s, beg+1, r, l-1)) return true;
        if(l+1<cols && !cur[r][l+1])
            if (search_tag(board,cur, s, beg+1, r, l+1)) return true;
    }
    cur[r][l] = false;
    return false;
}


bool exist(vector<vector<char>>& board, string word) {
    int row = board.size();
    int col = board[0].size();
    int len = word.size();
    bool res = false;
    if(row*col < len)
        return false;
    vector<vector<bool>> cur(row,vector<bool>(col,false));
    for(int i = 0; i < row; i++)
        for(int j = 0; j < col; j++){
            if(word[0] != board[i][j])
                continue;
            else{
                
                res = search_tag(board,cur,word,0,i,j);
                if(res == true)
                    return res;
            }
        }
    return res;
}
};


你可能感兴趣的:(LeetCode,C++,backtracking)