Word Search
Apr 18 '12
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的变种, 用visited保存访问过的位置.
[CODE]
public class Solution {
public boolean exist(char[][] board, String word) {
//init check
if(board==null || board.length==0 || board[0]==null || board[0].length==0) return false;
boolean[][] visited = new boolean[board.length][board[0].length];
for(int i=0; i<board.length; i++) {
for(int j=0; j<board[0].length; j++) {
if( search(board, visited, i, j, word) )return true;
}
}
return false;
}
private boolean search(char[][] board, boolean[][] visited, int x, int y, String word) {
if(word.length() == 0) return true;
if(x<0 || x>=board.length || y<0 || y>=board[0].length) {
return false;
}
if(visited[x][y] || board[x][y] != word.charAt(0)) return false;
visited[x][y] = true;
boolean b = search(board, visited, x-1, y ,word.substring(1) )
|| search(board, visited, x+1, y ,word.substring(1) )
|| search(board, visited, x, y-1 ,word.substring(1) )
|| search(board, visited, x, y+1 ,word.substring(1) );
if(b) return true;
else {
visited[x][y] = false;
return false;
}
}
}