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.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

AC code:

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        if (board.size() == 0) return false;
        int len = word.length();
        int row = board.size(), col = board[0].size();
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < col; ++j) {
                if (board[i][j] == word[0]) {
                    if (helper(i, j, word, 0, board))
                        return true;
                }
            }
        }
        return false;
    }
    
    bool helper(int x, int y, string& word, int index, vector<vector<char>>& board) {
        if (index >= word.length()) return true;
        if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size()) return false;
        if (board[x][y] == word[index++]) {
            char c = board[x][y];
            board[x][y] = '#';
            bool res = helper(x+1, y, word, index, board) || helper(x-1, y, word, index, board) ||
                       helper(x, y+1, word, index, board) || helper(x, y-1, word, index, board);
            board[x][y] = c;
            return res;
        }
        return false;
    }
};
Runtime: 20 ms, faster than 80.42% of C++ online submissions for Word Search.

 

 

posted @ 2018-10-24 15:47  Veritas_des_Liberty  阅读(223)  评论(0编辑  收藏  举报