码迷,mamicode.com
首页 > 其他好文 > 详细

79. Word Search

时间:2016-03-31 09:24:25      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

把表看成是一棵以左上角为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

标签:

原文地址:http://www.cnblogs.com/warmland/p/5339845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!