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

    }
};
}
Python 是一种流行的高级编程语言,因其简洁易读的语法和广泛的应用领域而受到开发者喜爱。LeetCode 是一个在线编程平台,专门用于算法和技术面试的准备,提供了大量的编程题目,包括数据结构、算法、系统设计等,常用于提升程序员的编程能力和解决实际问题的能力。 在 Python 中刷 LeetCode 题目通常涉及以下步骤: 1. **注册账户**:首先在 LeetCode 官网 (https://leetcode.com/) 注册一个账号,这样你可以跟踪你的进度和提交的代码。 2. **选择语言**:登录后,在个人主页设置中选择 Python 作为主要编程语言。 3. **学习和理解题目**:阅读题目描述,确保你理解问题的要求和预期输出。题目通常附有输入示例和预期输出,可以帮助你初始化思考。 4. **编写代码**:使用 Python 编写解决方案,LeetCode 提供了一个在线编辑器,支持实时预览和运行结果。 5. **测试和调试**:使用给出的测试用例来测试你的代码,确保它能够正确地处理各种边界条件和特殊情况。 6. **提交答案**:当代码完成后,点击 "Submit" 提交你的解法。LeetCode 会自动运行所有测试用例并显示结果。 7. **学习他人的代码**:如果遇到困难,可以查看社区中的其他优秀解法,学习他人的思路和技术。 8. **反复练习**:刷题不是一次性的事情,通过反复练习和优化,逐渐提高解题速度和代码质量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值