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 = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
- hui chao shi
public class Solution {
/*
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
private boolean ans = false;
public boolean exist(char[][] board, String word) {
// write your code here
if (board == null || board.length == 0 || board[0] == null || board[0].length == 0 || word == null) {
return false;
}
if (word.length() == 0) {
return true;
}
String cur = "";
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == word.charAt(0)) {
dfs(i, j, cur, board, word);
}
if (ans) {
return true;
}
}
}
return false;
}
public void dfs(int i, int j, String cur, char[][] board, String word) {
if (cur.length() == word.length()) {
ans = true;
return;
}
if (i < 0 || i >= board.length || j < 0 || j >= board[i].length) {
return;
}
if (board[i][j] != word.charAt(cur.length())) {
return;
}
if (board[i][j] == '#') {
return;
}
char current = board[i][j];
cur += board[i][j];
board[i][j] = '#';
dfs(i + 1, j, cur, board, word);
dfs(i - 1, j, cur, board, word);
dfs(i, j - 1, cur, board, word);
dfs(i, j + 1, cur, board, word);
board[i][j] = current;
cur = cur.substring(0, cur.length() - 1);
}
}
- changed to return type dfs, then passed
public class Solution {
/*
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
//private boolean ans = false;
public boolean exist(char[][] board, String word) {
// write your code here
if (board == null || board.length == 0 || board[0] == null || board[0].length == 0 || word == null) {
return false;
}
if (word.length() == 0) {
return true;
}
boolean result = false;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == word.charAt(0)) {
result = dfs(i, j, 0, board, word);
}
if (result) {
return true;
}
}
}
return false;
}
public boolean dfs(int i, int j, int start, char[][] board, String word) {
if (start >= word.length()) {
return true;
}
if (i < 0 || i >= board.length || j < 0 || j >= board[i].length) {
return false;
}
if (board[i][j] != word.charAt(start)) {
return false;
}
if (board[i][j] == '#') {
return false;
}
//cur += board[i][j];
board[i][j] = '#';
boolean result = dfs(i + 1, j, start + 1, board, word) ||
dfs(i - 1, j, start + 1, board, word) ||
dfs(i, j - 1, start + 1, board, word) ||
dfs(i, j + 1, start + 1, board, word);
board[i][j] = word.charAt(start);
return result;
}
}