首页 > 其他 > 详细

Word Search

时间:2016-06-29 06:34:22      阅读:217      评论:0      收藏:0      [点我收藏+]

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.

Example

Given board =

[
  "ABCE",
  "SFCS",
  "ADEE"
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

分析:
在board这个数组里,每个字符都可能是起始字符,所以我们得遍历所有字符,以它作为其实字符,如果该字符与target字符串第一个字符相同,然后我们在board数组里各个方向进行搜索。直到target最后一个字符被找到为止。
 
 1 public class Solution {
 2     /**
 3      * cnblogs.com/beiyeqingteng/
 4      */
 5     public boolean exist(char[][] board, String word) {
 6         if (board == null || board.length == 0 || board[0].length == 0) return false;
 7         if (word.length() == 0) return true;
 8 
 9         boolean[][] visited = new boolean[board.length][board[0].length];
10         boolean[] result = new boolean[1];
11         for (int i = 0; i < board.length; i++) {
12             for (int j = 0; j < board[0].length; j++) {
13                 if (board[i][j] == word.charAt(0)) {
14                     helper(board, i, j, word, 0, visited, result);
15                 }
16             }
17         }
18         return result[0];
19     }
20 
21     public void helper(char[][] board, int i, int j, String word, int index, boolean[][] visited, boolean[] result) {
22         
23         if (index == word.length()) {
24             result[0] = true;
25         }
26         
27         if (result[0]) return;
28         
29         if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return;
30 
31         if (visited[i][j] == false && board[i][j] == word.charAt(index)) {
32             visited[i][j] = true;
33             helper(board, i + 1, j, word, index + 1, visited, result);
34             helper(board, i - 1, j, word, index + 1, visited, result);
35             helper(board, i, j + 1, word, index + 1, visited, result);
36             helper(board, i, j - 1, word, index + 1, visited, result);
37             visited[i][j] = false;
38         }
39     }
40 }

 

参考请注明出处:cnblogs.com/beiyeqingteng/
 

Word Search

原文:http://www.cnblogs.com/beiyeqingteng/p/5625530.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!