Medium Word Search
26%
Accepted
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.
Have you met this question in a real interview?
Yes
Example
Given board =
[ "ABCE", "SFCS", "ADEE" ]
word =
word =
word =
"ABCCED"
, -> returns true
,word =
"SEE"
, -> returns true
,word =
"ABCB"
, -> returns false
.public class Solution {
/**
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
public boolean exist(char[][] board, String word) {
// write your code here
if(board == null || board.length == 0 || board[0].length == 0){
return false;
}
int m = board.length, n = board[0].length;
boolean[][] path = new boolean[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(!path[i][j] && _find(board, word, path, i, j, 0))
return true;
}
}
return false;
}
private boolean _find(char[][] board, String word, boolean[][] path, int i, int j, int idx){
if(word.charAt(idx) != board[i][j]) return false;
if(idx == word.length()-1) return true;
path[i][j] = true;
if(i - 1 >= 0 && i - 1 < board.length && j >= 0 && j < board[0].length && !path[i-1][j] && _find(board, word, path, i-1, j, idx+1)) return true;
if(i + 1 >= 0 && i+1 < board.length && j >= 0 && j < board[0].length && !path[i+1][j] && _find(board, word, path, i+1, j, idx+1)) return true;
if(i>= 0 && i < board.length && j-1 >= 0 && j-1 < board[0].length && !path[i][j-1] && _find(board, word, path, i, j-1, idx+1)) return true;
if(i >= 0 && i < board.length && j + 1 >= 0 && j + 1 < board[0].length && !path[i][j+1] && _find(board, word, path, i, j+1, idx+1)) return true;
path[i][j] = false;
return false;
}
}
No comments:
Post a Comment