LeetCode OJ 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 =

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

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

解答

其实就是个DFS,太水了以至于一遍就AC了。。。

下面是AC的代码:

class Solution {
public:
    int **flag;
    bool search(vector<vector<char>>& board, string word, int row, int col){
        if(row < 0 || row >= board.size() || col < 0 || col >= board[0].size()){
            return false;
        }
        if(word[0] == board[row][col] && flag[row][col] == 0){
            if(word.size() == 1){
                return true;
            }
            else{
                int length = word.size();
                flag[row][col] = 1;
                int ret = search(board, word.substr(1, length - 1), row - 1, col)
                    || search(board, word.substr(1, length - 1), row, col + 1)
                    || search(board, word.substr(1, length - 1), row + 1, col)
                    || search(board, word.substr(1, length - 1), row, col - 1);
                if(ret == true){
                    return true;
                }
                else{
                    flag[row][col] = 0;
                    return false;
                }
            }
        }
        else{
            return false;
        }
    }
    bool exist(vector<vector<char>>& board, string word) {
        int row = board.size();
        int col = board[0].size();
        flag = new int*[row];
        for(int i = 0; i < row; i++){
            flag[i] = new int[col];
            for(int j = 0; j < col; j++){
                flag[i][j] = 0;
            }
        }
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(search(board, word, i, j) == true){
                    return true;
                }
            }
        }
        return false;
    }
};

117

上一篇:【LeetCode】Longest Word in Dictionary through Deleting 解题报告


下一篇:[洛谷P2123]皇后游戏