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 dfs(string word, int row, int col)
{
    if(word.size() == 0) return true;
    if(col < 0 || col >= n || row < 0 || row >= m || board[row][col] != word[0]) return false;
     bool b1, b2, b3, b4;
     board[row][col] = ‘#‘;
     b1 = dfs(word.substr(1, word.size() - 1),row + 1, col);
     if(b1) return true;
     b2 = dfs(word.substr(1, word.size() - 1), row, col + 1);
     if(b2) return true;
     b3 = dfs(word.substr(1, word.size() - 1), row - 1, col);
     if(b3) return true;
     b4 = dfs(word.substr(1, word.size() - 1), row, col - 1);
     if(b4) return true;
     board[row][col] = word[0];
     return false;
}
    bool exist(vector<vector<char> > &board, string word) {
        this->board = board;
        m = board.size();
        if(m <= 0) return false;
        n = board[0].size();
        if(word.size() == 0) return true;
        bool re = false;
        for(int i = 0; i < m; ++i)
        for(int j = 0; j < n; ++j)
        {
             re = dfs(word,i,j);
             if(re == true) return true;
        }
        return re;
    }
    private:
    vector<vector<char> > board;
    int m, n;
};

跪了,300ms左右。。。要尝试bfs来弄下,看看如何。

Word Search

上一篇:绑定变量转换


下一篇:【GDI+编程--打印篇(三)】--分页打印