79. Word Search

Posted warmland

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了79. Word Search相关的知识,希望对你有一定的参考价值。

把表看成是一棵以左上角为root的树,进行dfs,用used存放访问是否

 1     public boolean exist(char[][] board, String word) {
 2         if(word == null || word.length() == 0) {
 3             return true;
 4         }
 5         if(board == null || board.length == 0 ||  board[0].length == 0) {
 6             return false;
 7         }
 8         boolean[][] used = new boolean[board.length][board[0].length];
 9         for(int row = 0; row < board.length; row++) {
10             for(int col = 0; col < board[0].length; col++) {
11                 if(search(board, word, 0, used, row, col)) {
12                     return true;
13                 }
14             }
15         }
16         return false;
17     }
18     
19     private boolean search(char[][] board, String word, int index, boolean[][] used, int row, int col) {
20         if(index == word.length()) { 
21             return true;
22         }
23         int rowNum = board.length;
24         int colNum = board[0].length;
25         if(row >= rowNum || col >= colNum || row < 0 || col < 0 || used[row][col] || board[row][col] != word.charAt(index)) {
26             return false;
27         }
28         used[row][col] = true;
29         if(search(board, word, index+1, used, row+1, col) || search(board, word, index+1, used, row-1, col) 
30                 || search(board, word, index+1, used, row, col+1) || search(board, word, index+1, used, row, col-1)) {
31             return true;
32         }
33         used[row][col] = false;
34         return false;
35     }

要注意下标从0开始

1.20行index == word.length().就是说已经搜索的超过这个word的范围了,所以为真。如果index == word.length()-1,那么最后一位其实还没有搜

2.25行,col>=colNum,不是>

以上是关于79. Word Search的主要内容,如果未能解决你的问题,请参考以下文章

79. Word Search

79. Word Search

LeetCode79. Word Search

79. Word Search

79. Word Search

79. Word Search