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

posted @ 2017-05-31 02:58  panini  阅读(152)  评论(0编辑  收藏  举报