Word Search

LeetCode Q 79 - 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.

Example:
board =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]

Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.

Solution : DFS

Time Complexity:O(n^2 4 3^(k-1)) = O(n^2 * 3^k).

Explanation: We start the word search over all n^2 nodes. For the first letter of the word search we can move in 4 directions but for every later one there are only three options (you can’t move back onto yourself).

Code:

boolean[][] visited;
public boolean exist(char[][] board, String word) {
	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 (dfs(board, word, 0, i, j)) return true;
		}
	}
	return false;
}

private boolean dfs(char[][] board, String word, int pos, int row, int col) {
	if (pos == word.length()) return true;

	if (row < 0 || row == board.length || col < 0 || col > board[0].length || 
	visited[row][col] || board[row][col] != word.charAt(pos)) 
		return false;

	visited[row][col] = true;
	if (dfs(board, word, pos + 1, row - 1, col) || 
	dfs(board, word, pos + 1, row + 1, col) || 
	dfs(board, word, pos + 1, row, col - 1) || 
	dfs(board, word, pos + 1, row, col + 1))
		return true;
	visited[row][col] = false;
	
	return
}

   Reprint policy


《Word Search》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC