zoukankan      html  css  js  c++  java
  • Leetcode中级算法-搜索(DFS,BFS)

    题目1 : 单词搜索

    给定一个二维网格和一个单词,找出该单词是否存在于网格中。

    单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

    示例:

    board =
    [
    [‘A’,’B’,’C’,’E’],
    [‘S’,’F’,’C’,’S’],
    [‘A’,’D’,’E’,’E’]
    ]

    给定 word = “ABCCED”, 返回 true.
    给定 word = “SEE”, 返回 true.
    给定 word = “ABCB”, 返回 false.

    解题思路:简单DFS,注意边界条件的判断和点的回溯(index和visted)

    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;
    class Solution
    {
      public:
        string str;
        vector<vector<char>> map;
        vector<vector<bool>> visted;
        int index = 1;
        int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        bool DFS(int x, int y, int deep)
        {
            auto row = map.size();
            auto col = map[0].size();
            auto len = str.size();
    
            if (deep == len && map[x][y] == str[len - 1])//这里是两个条件
            {
                return true;
            }
            for (int i = 0; i < 4; i++)
            {
                auto xx = x + dir[i][0];
                auto yy = y + dir[i][1];
                if (xx < 0 || xx >= row || yy < 0 || yy >= col || visted[xx][yy] || map[xx][yy] != str[index])
                    continue;
                else
                {
                    index++;
                    visted[xx][yy] = true;
                    if (DFS(xx, yy, deep + 1))
                        return true;
                    visted[xx][yy] = false ;
                    index--;
                }
            }
            return false;
        }
        bool exist(vector<vector<char>> &board, string word)
        {
            auto row = board.size();
            auto col = board[0].size();
    
            vector<bool> temp(col, false);
            vector<vector<bool>> temp_visted(row, temp);
    
            str = word;
            map = board;
            visted = temp_visted;
    
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    if (visted[i][j] == false && board[i][j] == word[0])
                    {
                        visted[i][j] = true;
                        if (DFS(i, j, 1))
                            return true;
                        visted[i][j] = false;
                    }
                }
            }
            return false;
        }
    };
  • 相关阅读:
    合并报表优化记录
    如何在后台代码中执行原生sql?
    eclipse从数据库逆向生成Hibernate实体类
    用Eclipse进行远程Debug代码
    hibernate自动生成数据库表
    hibernate自动生成数据库表
    php通过UNIX源码编译安装
    php设置方法
    php其他配制选项
    终于做出了目录认证!
  • 原文地址:https://www.cnblogs.com/Tattoo-Welkin/p/10335266.html
Copyright © 2011-2022 走看看