LeetCode 79. Word Search

1. 题目描述

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.

2. 解题思路

拿到这个问题首先想到的是 DFS 搜索, 由此可以很容易的给出代码

3. code

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

private:
    bool _exist(vector<vector<char>>& board, string word, int depth, int row, int col){
        if (depth == word.size())
            return true;

        if (row >= board.size() || col >= board[0].size() || word[depth] != board[row][col])
            return false;       

        char tmp = board[row][col];
        board[row][col] = 0;
        bool ret = _exist(board, word, depth + 1, row + 1, col);
        if (!ret)
            ret = _exist(board, word, depth + 1, row - 1, col);
        if (!ret)
            ret = _exist(board, word, depth + 1, row, col + 1);
        if (!ret)
            ret = _exist(board, word, depth + 1, row, col - 1);
        board[row][col] = tmp;

        return ret;
    }
};

4. 大神解法

一样的思路

public boolean exist(char[][] board, String word) {
    char[] w = word.toCharArray();
    for (int y=0; y<board.length; y++) {
        for (int x=0; x<board[y].length; x++) {
            if (exist(board, y, x, w, 0)) return true;
        }
    }
    return false;
}

private boolean exist(char[][] board, int y, int x, char[] word, int i) {
    if (i == word.length) return true;
    if (y<0 || x<0 || y == board.length || x == board[y].length) return false;
    if (board[y][x] != word[i]) return false;
    board[y][x] ^= 256;
    boolean exist = exist(board, y, x+1, word, i+1)
        || exist(board, y, x-1, word, i+1)
        || exist(board, y+1, x, word, i+1)
        || exist(board, y-1, x, word, i+1);
    board[y][x] ^= 256;
    return exist;
}

你可能感兴趣的:(LeetCode)