1. 程式人生 > >【LeetCode】110.Word Search

【LeetCode】110.Word Search

題目描述(Medium)

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.

題目連結

https://leetcode.com/problems/word-search/description/

Example 1:

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.

演算法分析

注意幾個終止條件,越界、已訪問、不相等。

提交程式碼:

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        if (board.empty() || board[0].empty()) return false;
        const int m = board.size();
        const int n = board[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if(DFSWordSearch(board, visited, word, 0, i, j))
                    return true;
            }
        }
        return false;
    }

private:
    bool DFSWordSearch(vector<vector<char>>& board, vector<vector<bool>>& visited,
                      string& word, int index, int x, int y) {
        if (index == word.size()) return true;
        if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return false;
        if (visited[x][y]) return false;
        if (word[index] != board[x][y]) return false;
        visited[x][y] = true;
        
        bool result = DFSWordSearch(board, visited, word, index + 1, x + 1, y)
            || DFSWordSearch(board, visited, word, index + 1, x - 1, y)
            || DFSWordSearch(board, visited, word, index + 1, x, y + 1)
            || DFSWordSearch(board, visited, word, index + 1, x, y - 1);
        
        visited[x][y] = false;
        return result;
    }
};