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
1
2
3
4
5
6
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
Solution
Java: board[i][j] ^= 256,把字母变成非法数字
(Word-Search.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
public boolean exist ( char [][] board , String word ) {
int m = board . length ;
int n = board [ 0 ]. length ;
char [] w = word . toCharArray ();
for ( int i = 0 ; i < m ; i ++){
for ( int j = 0 ; j < n ; j ++){
if ( dfs ( board , i , j , w , 0 ))
return true ;
}
}
return false ;
}
public boolean dfs ( char [][] board , int row , int col , char [] word , int index ){
if ( index == word . length ) return true ;
if ( row < 0 || col < 0 || row == board . length || col == board [ 0 ]. length ) return false ;
if ( word [ index ] != board [ row ][ col ]) return false ;
board [ row ][ col ] ^= 256 ;
boolean ret = dfs ( board , row , col + 1 , word , index + 1 ) ||
dfs ( board , row + 1 , col , word , index + 1 ) ||
dfs ( board , row , col - 1 , word , index + 1 ) ||
dfs ( board , row - 1 , col , word , index + 1 );
board [ row ][ col ] ^= 256 ;
return ret ;
}
}
Python: Use “.” to replace the board[i][j] when it is visited.
(Word-Search.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution :
# @param {character[][]} board
# @param {string} word
# @return {boolean}
def exist ( self , board , word ):
self . b , self . w , self . m , self . n , self . wLen = board , word , len ( board ), len ( board [ 0 ]), len ( word )
for i in xrange ( self . m ):
for j in xrange ( self . n ):
if self . isFound ( 0 , i , j ):
return True
return False
def isFound ( self , k , x , y ):
if x < 0 or y < 0 or x >= self . m or y >= self . n or self . b [ x ][ y ] == '.' or self . b [ x ][ y ] != self . w [ k ]:
return False
if k == self . wLen - 1 :
return True
tmp , self . b [ x ][ y ] = self . b [ x ][ y ], '.'
if self . isFound ( k + 1 , x - 1 , y ) or self . isFound ( k + 1 , x + 1 , y ) or \
self . isFound ( k + 1 , x , y - 1 ) or self . isFound ( k + 1 , x , y + 1 ):
return True
self . b [ x ][ y ] = tmp
return False