题解 | #童谣寻找问题#

童谣寻找问题

https://www.nowcoder.com/practice/2537c84de0034d019b1679cf7bfcf776

#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param board char字符型vector<vector<>> 
     * @param word string字符串 
     * @return bool布尔型
     */

    vector<pair<int,int>> v = {{-1,0},{1,0},{0,-1},{0,1}};
    bool ans = false;

    void dfs(vector<vector<char>>& board, int i, int j, string word, int index, vector<vector<bool>> flag, string str)
    {
        if(i<0 || i>=board.size() || j<0 || j>=board[0].size())
            return;

        if(str == word)
        {
            ans = true;
            return;
        }

        if(board[i][j]==word[index] && !flag[i][j])
        {
            flag[i][j] = true;
            str.push_back(word[index]);
            for(auto [t_i,t_j]:v)
                dfs(board, i+t_i, j+t_j, word, index+1, flag, str);
        }
    }

    bool exist(vector<vector<char> >& board, string word) {
        // write code here
        
        // 深度优先搜索
        int row = board.size();
        int col = board[0].size();
        // 避免重复遍历
        vector<vector<bool>> flag(row,vector<bool>(col,false));
        string str = "";

        for(int i=0; i<row; ++i)
        {
            for(int j=0; j<col; ++j)
            {
                if(board[i][j]==word[0])
                    dfs(board, i, j, word, 0, flag, str);
            }
        }

        return ans;
    }
};

虚数五行区解题中心 文章被收录于专栏

非淡泊无以明志,非宁静无以致远

全部评论

相关推荐

02-13 14:30
四川大学 Java
Java抽象带篮子:简历怎么写可以看看我发的帖子,你先照着优化下简历吧
点赞 评论 收藏
分享
野猪不是猪🐗:把你的学校加黑,加粗,斜体,下划线,描边,内阴影,内发光,投影,外发光,再上渐变色,居中,放大到最大字号,再把简历里其它内容删了,就行了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务