leetcode -- 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.

[解题思路]

DFS 深度优先搜索

 1 public boolean exist(char[][] board, String word) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         int wLen = word.length();
 5         if(wLen == 0){
 6             return true;
 7         }
 8         
 9         int row = board.length;
10         if(row == 0){
11             return false;
12         }
13         int col = board[0].length;
14         for(int i = 0; i < row; i++){
15             for(int j = 0; j < col; j++){
16                 if(board[i][j] == word.charAt(0)){
17                     boolean found = find(board, word, new boolean[row][col], 0, i, j);
18                     if(found){
19                         return found;
20                     }
21                 }
22             }
23         }
24         return false;
25         
26     }
27     
28     public boolean find(char[][] board, String word, boolean[][] visited, int depth,
29             int i, int j){
30             if(depth == word.length()){
31                 return true;
32             }    
33                 
34             if(i < 0 || i >= board.length || j < 0 || j >= board[0].length 
35                 || (visited[i][j] == true) || word.charAt(depth) != board[i][j]){
36                 return false;
37             }
38             
39             visited[i][j] = true;
40             
41             // top, down, left, right
42             return find(board, word, visited, depth + 1, i - 1, j) ||
43                 find(board, word, visited, depth + 1, i + 1, j) ||
44                 find(board, word, visited, depth + 1, i, j - 1) ||
45                 find(board, word, visited, depth + 1, i, j + 1);
46     }

网上关于深度优先搜索的总结帖:

http://cuijing.org/interview/leetcode/summary-of-dfs-and-bfs-in-leetcode.html

http://leetcodenotes.wordpress.com/2013/08/24/leetcode-word-search-%E4%BA%8C%E7%BB%B4%E7%9F%A9%E9%98%B5%E6%89%BE%E9%87%8C%E9%9D%A2%E7%9A%84%E5%8D%95%E8%AF%8D/

posted @ 2013-08-30 23:16  feiling  阅读(460)  评论(1编辑  收藏  举报