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     }

     

  • 相关阅读:
    数据结构--树链剖分准备之LCA
    FancyBox的使用技巧 (汇总)
    轮播效果汇总
    媒体查询
    网页效果总结
    sublime使用技巧总结
    js面向对象
    【STL】牛客练习赛16 F-选值 (手写二分应该也能过)
    【数论】【HDU 2048】神、上帝以及老天爷 【错排公式】
    【STL】【HDU2024】C语言合法标识符【水题】
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3439565.html
Copyright © 2011-2022 走看看