Word Search

Posted

tags:

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

 1 public class Solution {
 2     public boolean exist(char[][] board, String word) {
 3         if(!isValidBoard(board) || word == null || word.length() == 0) {
 4             return false;
 5         }
 6         
 7         boolean[][] visitedMap = new boolean[board.length][board[0].length];
 8         for(int i = 0; i < board.length; i++) {
 9             for(int j = 0; j < board[i].length; j++) {
10                 if(contains(board, visitedMap, word, i, j, 0)) {
11                     return true;
12                 }
13             }
14         }
15         
16         return false;
17     }
18     
19     private boolean isValidBoard(char[][] board) {
20         if(board == null || board.length == 0 || board[0] == null || board[0].length == 0) {
21             return false;
22         } else {
23             return true;
24         }
25     }
26     
27     private boolean contains(char[][] board, boolean[][] visitedMap, String word, int i, int j, int index) {
28         if(index >= word.length() || visitedMap[i][j] == true) {
29             return false;
30         } else if(index == word.length()-1 && board[i][j] == word.charAt(index)) {
31             return true;
32         } 
33         
34         if(board[i][j] == word.charAt(index)) {
35             visitedMap[i][j] = true;
36             
37             // upper
38             if(i > 0 && contains(board, visitedMap, word, i-1, j, index+1)) {
39                 return true;
40             }
41             
42             // down
43             if(i < board.length-1 && contains(board, visitedMap, word, i+1, j, index+1)) {
44                 return true;
45             }
46             
47             // left
48             if(j > 0 && contains(board, visitedMap, word, i, j-1, index+1)) {
49                 return true;
50             }
51             
52             // right
53             if(j < board[i].length-1 && contains(board, visitedMap, word, i, j+1, index+1)) {
54                 return true;
55             }
56             
57             visitedMap[i][j] = false;
58         }
59         
60         return false;
61     }
62     
63 }

 

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

刷题79. Word Search

LeetCode 79. Word Search

Word Search

79. Word Search

79. Word Search

79. Word Search/212. Word Search II--图的back tracking -- tier tree 待续