Leetcode: 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

分析:DFS+Backtracking。这道题与sudoku solver类似,都可以作为DFS+Backtracking的模板。代码如下:

class Solution {
public:
    vector<vector<bool> > used;
    bool exist(vector<vector<char> > &board, string word) {
       used = vector<vector<bool> >(board.size(), vector<bool>(board[0].size(), false));
       for(int i = 0; i < board.size(); i++)
            for(int j = 0; j < board[0].size(); j++)
                if(word_search(board, word, i, j)) return true;
        return false;
    }
    
    bool word_search(vector<vector<char> > &board, string word, int i, int j){
        if(word == "") return true;
        if(i < 0 || i >= board.size() || j < 0 || j >= board[0].size()) return false;
        if(used[i][j] || word[0] != board[i][j]) return false;
        used[i][j] = true;
        if(word_search(board, word.substr(1), i,j-1) || word_search(board, word.substr(1), i-1, j)
            || word_search(board, word.substr(1), i, j+1) || word_search(board, word.substr(1), i+1,j))
            return true;
        used[i][j] = false;
        return false;
    }
};

 

posted on 2014-12-07 00:47  Ryan-Xing  阅读(112)  评论(0编辑  收藏  举报