【LeetCode】79. Word Search 在矩陣中搜索單詞

一、概述

輸入一個矩陣,矩陣元素爲大寫字母;輸入一個字符串,然後在矩陣中尋找出上下左右相鄰的元素,這些相鄰的元素能夠按序組成這個字符串。

題目不難,和判斷孤島那題類似。就是debug氣死我了。

二、分析

就是遍歷一次矩陣,然後DFS即可。

DFS只有一點要注意:條件判斷中條件的選取,首先因爲要上下左右,所以要判斷下標不能溢出;然後再判斷是不是之前走過;最後判斷是不是我們要的字母。這三者判斷是必有的。爲了防止時間過長,需要加上flag判斷。當我們找到了所需的序列,就要把flag置爲true。然後如果flag變爲true,那麼就不進行其餘的判斷,剪了很多枝。

代碼如下:

class Solution {
    bool res=false;
    void DFS(vector<vector<char>>& board,int x,int y,int loc,string& word)
    {
        if(loc==word.size())
            res=true;
        if(!res&&x>0&&board[y][x-1]!='x'&&board[y][x-1]==word[loc])
        {
            board[y][x]='x';
            DFS(board,x-1,y,loc+1,word);
            board[y][x]=word[loc-1];
        }
        if(!res&&y>0&&board[y-1][x]!='x'&&board[y-1][x]==word[loc])
        {
            board[y][x]='x';
            DFS(board,x,y-1,loc+1,word);
            board[y][x]=word[loc-1];
        }
        if(!res&&y<board.size()-1&&board[y+1][x]!='x'&&board[y+1][x]==word[loc])
        {
            board[y][x]='x';
            DFS(board,x,y+1,loc+1,word);
            board[y][x]=word[loc-1];
        }
        if(!res&&x<board[0].size()-1&&board[y][x+1]!='x'&&board[y][x+1]==word[loc])
        {
            board[y][x]='x';
            DFS(board,x+1,y,loc+1,word);
            board[y][x]=word[loc-1];
        }
    }
public:
    bool exist(vector<vector<char>>& board, string word) {
        if(board.size()==0||word.size()==0)
            return false;
        for(int x=0;x<board[0].size();++x)
        {
            for(int y=0;y<board.size();++y)
            {
                if(board[y][x]==word[0])
                {
                    DFS(board,x,y,1,word);
                    if(res==true)
                        return res;
                }
            }
        }
        return res;
    }
};

PS:在主函數調用之後一定要判斷是不是已經找到了,找到就return就行。這個坑死我了。

三、總結

很簡單的模板題。

 

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