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 board =
[
"ABCE",
"SFCS",
"ADEE"
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
DFS - with additional space for visited[][] matrix (12ms 52.97% AC)
class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
}
if (word.length() == 0) {
return true;
}
int M = board.length;
int N = board[0].length;
boolean[][] visited=new boolean[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (existHelper(board, visited, i, j, word, 0)) return true;
}
}
return false;
}
private boolean existHelper(char[][] board, boolean[][] visited, int row, int col, String 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.charAt(index) != board[row][col] || visited[row][col]) return false;
visited[row][col] = true;
int[] dx = new int[] {0, 1, 0, -1};
int[] dy = new int[] {1, 0, -1, 0};
for (int i = 0; i < dx.length; i++) {
if ( existHelper(board, visited, row + dx[i], col + dy[i], word, index + 1)) {
return true;
}
}
visited[row][col] = false;
return false;
}
}
DFS - using temporary '#' mark visited element (15 ms 36.92% AC)
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) {
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
}
if (word.length() == 0) {
return true;
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == word.charAt(0)) {
boolean result = dfs(board, word, i, j, 0);
if (result) {
return true;
}
}
}
}
return false;
}
private boolean dfs(char[][] board, String word, int i, int j, int k) {
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
}
if (word.length() == 0) {
return true;
}
if (word.length() == k) {
return true;
}
boolean result = false;
if (insideBoard(board, i, j) && board[i][j] == word.charAt(k)) {
char temp = board[i][j];
board[i][j] = '#';
result = dfs(board, word, i + 1, j, k + 1) ||
dfs(board, word, i - 1, j, k + 1) ||
dfs(board, word, i, j + 1, k + 1) ||
dfs(board, word, i, j - 1, k + 1);
board[i][j] = temp;
}
return result;
}
private boolean insideBoard(char[][] board, int i, int j) {
return (i >= 0 && i < board.length && j >= 0 && j < board[0].length);
}
}