Somebody has written a better summary than I, see here
Nevermind, I will just write down my thoughts and notes.
Problem description quoted from the above citation:
Word Search
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.
Idea: The solution breaks into two big steps:
- First, find a match in the dictionary board for the beginning letter of target string
- From that beginning letter, using DFS to visit its neighbours and compare the continued letters until the end of the word
public class Solution {
public boolean exist(char[][] board, String word) {
boolean isEmpty = !(board.length != 0 && board[0].length != 0);
if (isEmpty && word.length() == 0) return true;
if (isEmpty) return false;
char[] target = word.toCharArray();
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 (board[i][j] != target[0]) {
continue;
}
if (searchFrom(board, i, j, target, 0, visited)) {
return true;
}
}
}
return false;
}
private boolean searchFrom(char[][] board, int i, int j,
char[] target, int target_i, boolean[][] visited) {
if (target_i == target.length)
return true;
boolean inBound = i >= 0 && i < board.length && j >= 0 && j < board[0].length;
if (!inBound)
return false;
if (visited[i][j])
return false;
if (board[i][j] != target[target_i])
return false;
int[][] moves = new int[][] { {0, 1}, {0, -1}, {1, 0}, {-1, 0} };
visited[i][j] = true;
for(int[] move : moves) {
if (searchFrom(board, i + move[0], j + move[1], target, target_i + 1, visited)) {
return true;
}
}
visited[i][j] = false;
return false;
}
}