日常刷题 leetcode 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.

Example:

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.
不愧是通过率只有26%的题,还是有点难度的。做了两个小时,想思路加调bug,终于按自己的思路做出来了,已经半夜12点20了,实在太困,不能把leetcode最优解法发出来了,先附上自己的代码以及思路,明日再做后续工作。
思路:
回溯法,遍历board每个元素,头字母符合的就进入递归体,递归体内,可行路径走得通的就继续递归,递归到底有完成匹配的路径就直接返回true,否则等所有可走的路都走完了也没有匹配完word的时候,再返回false;
算法执行时间:96ms(蛋疼)

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        if (word.empty())return false;
        vector<pair<int, int>>work;
        for (int i = 0; i<board.size(); ++i) {
            for (int j = 0; j<board[i].size(); ++j) {
                if (word[0] == board[i][j]) {
                    if (survey(board, i, j, word, 0, work) == true)
                        return true;
                    else
                        continue;
                }
            }
        }
        return false;
    }
    bool survey(vector<vector<char>>& board, int i, int j, string word, int k, vector<pair<int, int>> &work) {
        if (k + 1 == word.size())
            return true;
        work.push_back({ i,j });
        auto nexts = search(board, i, j, word, k, work);
        for (auto p : nexts) {
            if (board[p.first][p.second] == word[k + 1]) {
                if (survey(board, p.first, p.second, word, k + 1, work) == true)
                    return true;
                else
                    continue;
            }
        }
        work.pop_back();
        return false;
    }
    vector<pair<int, int>> search(vector<vector<char>>& board, int i, int j, string word, int k, vector<pair<int, int>> &work) {
        vector<pair<int, int>> nexts;
        auto dests = scan(i, j);
        for (auto p : dests) { //对可行路径进行违规筛选   
            pair<int, int>pos = { p.first,p.second };
            if (p.first >= 0 && p.first<board.size() && p.second >= 0 && p.second <board[i].size() && !review(work, pos)) {
                nexts.push_back(pos);
            }
        }
        return nexts;
    }
    vector<pair<int, int>> scan(int i, int j) {
        vector<pair<int, int>> dests;
        dests.push_back({ i - 1,j });
        dests.push_back({ i + 1,j });
        dests.push_back({ i,j - 1 });
        dests.push_back({ i,j + 1 });
        return dests;
    }
    bool review(vector<pair<int, int>> &work, pair<int, int> pos) {
        for (auto iter = work.begin(); iter != work.end(); ++iter) {
            if (pos == *iter)
                return true;
        }
        return false;
    }
};

第二天晨起,下面发布最优代码
该解法与上述解法的优化之处在于,没有用work辅助空间存储每次递归走过的路径,每次递归直接修改board,比如访问过board[0][0]后,就将board[0][0]=’\0’.然后在递归的时候,可在O(1)时间内判断路径是否合法,并且不需要额外的辅助空间。
算法运行时间:24ms

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

    }

    //从节点board[i][j]开始查找word
    bool backtrack(vector<vector<char>>& board,string& word,int i,int j,int pos)
    {
        int height=board.size();
        int width=board[0].size();

        if(i<0||j<0||i>=height||j>=width||board[i][j]=='\0'||board[i][j]!=word[pos])
            return false;
        if(pos==word.size()-1)
            return true;

        char t=board[i][j];
        board[i][j]='\0';

        if(backtrack(board,word,i,j+1,pos+1)||backtrack(board,word,i+1,j,pos+1)||backtrack(board,word,i-1,j,pos+1)||backtrack(board,word,i,j-1,pos+1))
            return true;

        board[i][j]=t;
        return false;

    }
};
}

猜你喜欢

转载自blog.csdn.net/qq_36946274/article/details/80788425
今日推荐