zoukankan      html  css  js  c++  java
  • 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.

    For example,
    Given board =

    [
      ["ABCE"],
      ["SFCS"],
      ["ADEE"]
    ]
    

    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.

    思路:

    DFS。

    先找到一个等于word[0]的坐标作为开始点,然后以这个点开始往四周开始查找。用visited数组记录是否访问过某个点,避免循环访问。

    代码:

     1     bool exist(int x, int y, string word, int index, vector<vector<bool> > &visited, vector<vector<char> > &board){
     2         if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size())
     3             return false;
     4         if(board[x][y] != word[index] || visited[x][y])
     5             return false;
     6         if(index == word.length()-1)
     7             return true;
     8         visited[x][y] = true;
     9         bool result = exist(x-1, y, word, index+1, visited, board) 
    10                    || exist(x+1, y, word, index+1, visited, board)
    11                    || exist(x, y-1, word, index+1, visited, board)
    12                    || exist(x, y+1, word, index+1, visited, board);
    13         visited[x][y] = false;
    14         return result;
    15     }
    16     bool exist(vector<vector<char> > &board, string word) {
    17         // IMPORTANT: Please reset any member data you declared, as
    18         // the same Solution instance will be reused for each test case.
    19         int l = word.length();
    20         if(l == 0)
    21             return true;
    22         int m = board.size();
    23         if(m == 0)
    24             return false;
    25         int n = board[0].size();
    26         if(n == 0)
    27             return false;
    28         vector<vector<bool> > visited(m, vector<bool>(n, false));
    29         for(int i = 0; i < m; i++){
    30             for(int j = 0; j < n; j++){
    31                 if(board[i][j] == word[0] && exist(i, j, word, 0, visited, board)){
    32                     return true;
    33                 }
    34             }
    35         }
    36         return false;
    37     }

     

  • 相关阅读:
    .net core 3.1 过滤器(Filter) 和中间件和AOP面向切面拦截器
    socket通信框架——boost asio
    远程过程调用框架——gRPC
    数据序列化工具——flatbuffer
    springboot项目启动----8080端口被占用排雷经过
    如何配置HOSTS文件
    使用线程Callable实现分段获取一个url连接的资源数据
    Socket网络编程课件
    (6)优化TCP编写 服务器端同时支持多个客户端同时访问
    SpringBoot配置属性之Security
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3439565.html
Copyright © 2011-2022 走看看