zoukankan      html  css  js  c++  java
  • Word Search leetcode java

    题目

    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.

    题解

     这道题分析看,就是一个词,在一行出现也是true,一列出现也是true,一行往下拐弯也是true,一行往上拐弯也是true,一列往左拐弯也是true,一列往右拐弯也是true。所以是要考虑到所有可能性,基本思路是使用DFS来对一个起点字母上下左右搜索,看是不是含有给定的Word。还要维护一个visited数组,表示从当前这个元素是否已经被访问过了,过了这一轮visited要回false,因为对于下一个元素,当前这个元素也应该是可以被访问的。

    代码如下:

     1     public boolean exist(char[][] board, String word) {
     2         int m = board.length;  
     3         int n = board[0].length;  
     4         boolean[][] visited = new boolean[m][n];  
     5         for (int i = 0; i < m; i++) {  
     6             for (int j = 0; j < n; j++) {  
     7                 if (dfs(board, word, 0, i, j, visited))  
     8                     return true;  
     9             }  
    10         }  
    11         return false;  
    12     }
    13     
    14     public boolean dfs(char[][] board, String word, int index, int rowindex, int colindex, boolean[][] visited) {  
    15         if (index == word.length())  
    16             return true;  
    17         if (rowindex < 0 || colindex < 0 || rowindex >=board.length || colindex >= board[0].length)  
    18             return false;  
    19         if (visited[rowindex][colindex])  
    20             return false;  
    21         if (board[rowindex][colindex] != word.charAt(index))  
    22             return false;  
    23         visited[rowindex][colindex] = true;  
    24         boolean res = dfs(board, word, index + 1, rowindex - 1, colindex,  
    25                 visited)  
    26                 || dfs(board, word, index + 1, rowindex + 1, colindex, visited)  
    27                 || dfs(board, word, index + 1, rowindex, colindex + 1, visited)  
    28                 || dfs(board, word, index + 1, rowindex, colindex - 1, visited);  
    29         visited[rowindex][colindex] = false;  
    30         return res;  
    31             }

     Reference:http://blog.csdn.net/yiding_he/article/details/18893621

  • 相关阅读:
    管理技巧,绩效考核自评怎么写
    网站运营文章LIST
    搜索引擎算法研究专题六:HITS算法
    搜索引擎算法研究专题五:TF-IDF详解
    搜索引擎算法研究专题七:Hilltop算法
    搜索引擎算法研究专题四:随机冲浪模型介绍
    搜索引擎算法研究专题三:聚集索引与非聚集索引介绍
    利用Lucene.net搜索引擎进行多条件搜索的做法
    五大主流数字币钱包:imToken数字货币钱包,Bitcoin core钱包,BTS网页版钱包,AToken轻钱包,Blockchain
    Java 9 逆天的十大新特性
  • 原文地址:https://www.cnblogs.com/springfor/p/3883942.html
Copyright © 2011-2022 走看看