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

    链接:  http://leetcode.com/problems/word-search/

    5/30/2017

    20ms, 25%

    注意

    第27行的判断最好先进行,不要在进入hasMatch部分才判断周围的boundary。原因没想好,但是否则的话通不过。

    第31-34行可以减少判断

     1 public class Solution {
     2     boolean[][] visited;
     3     public boolean exist(char[][] board, String word) {
     4         if (board == null || board.length == 0 || board[0].length == 0) {
     5             return false;
     6         }
     7         if (word == null || word.equals("")) {
     8             return true;
     9         }
    10 
    11         visited = new boolean[board.length][board[0].length];
    12 
    13         for (int i = 0; i < board.length; i++) {
    14             for (int j = 0; j < board[0].length; j++) {
    15                 if (dfs(board, i, j, word, 0)) {
    16                     return true;
    17                 }
    18             }
    19         }
    20         return false;
    21     }
    22 
    23     private boolean dfs(char[][] board, int i, int j, String word, int index) {
    24         if (index == word.length()) {
    25             return true;
    26         }
    27         if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(index) || visited[i][j]) {
    28             return false;
    29         }
    30         visited[i][j] = true;
    31         boolean hasMatch = dfs(board, i + 1, j, word, index + 1)
    32                         || dfs(board, i, j + 1, word, index + 1)
    33                         || dfs(board, i - 1, j, word, index + 1)
    34                         || dfs(board, i, j - 1, word, index + 1);
    35         if (hasMatch) {
    36             return true;
    37         }
    38         visited[i][j] = false;
    39         return false;
    40     }
    41 }

    更多讨论

    https://discuss.leetcode.com/category/87/word-search

  • 相关阅读:
    我的游戏开发工作生涯要开始了
    关于碰撞检测和物理引擎
    关于havok
    认识多渲染目标(Multiple Render Targets)技术
    无限分级的tree
    运用ThreadLocal解决jdbc事务管理
    盒子模型 计算
    监听域对象
    爱恨原则 就近原则 (LVHA)
    java database connection
  • 原文地址:https://www.cnblogs.com/panini/p/6922399.html
Copyright © 2011-2022 走看看