LeetCode 79. Word Search

這篇文章是 LeetCode 79. Word Search.md 的分析與解法。

問題描述

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.

這道題的意思就是在給定的字母板上尋找給定的單詞,規則是從一個字母開始垂直或者水平方向上開始尋找,同一個位置的字母只能在路徑上經過一次。

問題分析

這個問題首先能想到的方法就是暴力搜索,從字母板的(0, 0)位置開始搜索,到(n, n)位置結束。如果在搜索的過程中找到了給定的單詞就直接返回。

以下圖爲例,假設我們要搜索的單詞是『BED』,搜索順序爲『上下左右』:

搜索過程如下:

  1. 從(0, 0)位置的 A 開始搜索,A 與給定單詞的[0]位置的字母不匹配,到(1, 0)位置;
  2. (1, 0)位置的 B 與給定單詞的[0]位置的字母相同,按照 B 的上下左右的方向依次搜索,已經經過的位置不再搜索;
  3. 搜索至(1,1)位置的 E,與給定單詞的[1]的字母相同,按照 E 的上下左右的方向依次搜索,已經經過的位置不再搜索;
  4. 直到搜索到 D,完成 BED 的搜索,返回。

代碼實現

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

    bool search(vector<vector<char>>& board, string word, int x, int y, int pos){
        if(pos == word.length()){
            return true;
        }
        if(x < 0 || y < 0 || y >= board[x].size() || x >= board.size()){
            return false;
        }
        if(board[x][y] != word[pos]){
            return false;
        }
        char temp = board[x][y];
        board[x][y] = '*';

        bool result = search(board, word, x-1, y, pos+1)
        || search(board, word, x+1, y, pos+1)
        || search(board, word, x, y+1, pos+1)
        || search(board, word, x, y-1, pos+1);

        board[x][y] = temp;

        return result;
    }
};

本文的完整代碼詳見我的 GitHub


本文的版權歸作者 羅遠航 所有,採用 Attribution-NonCommercial 3.0 License。任何人可以進行轉載、分享,但不可在未經允許的情況下用於商業用途;轉載請註明出處。感謝配合!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章