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 class Solution { 2 public boolean exist(char[][] board, String word) { 3 if(word == null) 4 return true; 5 if(board.length == 0) 6 return false; 7 8 for(int i = 0; i < board.length; i++){ 9 for(int j = 0; j < board[0].length; j++){ 10 if(board[i][j] == word.charAt(0)){ 11 if(find(0, word, i, j, new boolean[board.length][board[0].length], board)) 12 return true; 13 } 14 } 15 } 16 return false; 17 } 18 19 public boolean find(int depth, String word, int i, int j, boolean[][] visited, char[][] board){ 20 if(depth == word.length()) 21 return true; 22 23 if( i<0 || i>=board.length || j<0 || j>=board[0].length || visited[i][j] 24 || board[i][j] != word.charAt(depth)){ 25 return false; 26 } 27 28 visited[i][j] = true; 29 30 boolean res = find(depth+1, word, i-1, j, visited, board) || 31 find(depth+1, word, i+1, j, visited, board) || 32 find(depth+1, word, i, j-1, visited, board) || 33 find(depth+1, word, i , j+1, visited, board); 34 if(res){ 35 return true; 36 }else{ 37 visited[i][j] = false; 38 return false; 39 } 40 } 41 }
空间优化 HashSet
public class Solution { public boolean exist(char[][] board, String word) { if(word == null || word.length() < 1) return false; HashSet<Integer> done = new HashSet<Integer>(); for(int i = 0; i < board.length; i++) for(int j =0; j < board[0].length; j++){ if(generate(board, i, j, 0, word, done)) return true; } return false; } private boolean generate(char[][] board, int row, int column, int depth, String word, HashSet<Integer> done){ if(row < 0 || column < 0 || row >= board.length || column >= board[0].length) return false; int loc = row * board[0].length + column; if(done.contains(loc)) return false; if(board[row][column] == word.charAt(depth)){ if(depth == word.length()-1) return true; done.add(loc); if(generate(board, row+1, column, depth+1,word,done)) return true; if(generate(board, row, column+1, depth+1,word,done)) return true; if(generate(board, row-1, column, depth+1,word,done)) return true; if(generate(board, row, column-1, depth+1,word,done)) return true; done.remove(loc); } return false; } }
ref: http://www.cnblogs.com/feiling/p/3292649.html
网上关于深度优先搜索的总结帖:
http://cuijing.org/interview/leetcode/summary-of-dfs-and-bfs-in-leetcode.html