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.

For example,
Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

public class Solution {
    public boolean exist(char[][] board, String word) {
        if (word == null || word.length() == 0) return true;
        if (board == null || board.length == 0 || board[0].length == 0) return false;
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[0].length; col++) {
                if (board[row][col] == word.charAt(0) && dfs(board, word, 0, row, col)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    public boolean dfs(char[][] board, String word, int level, int row, int col) {
        if (level == word.length()) return true;
        if (row < 0 || row >= board.length || col < 0 || col >= board[row].length) return false;
        if (board[row][col] != word.charAt(level)) return false;
        board[row][col] = '#';  // Must mark item visited on the board.
        boolean result = dfs(board, word, level + 1, row - 1, col) ||
                         dfs(board, word, level + 1, row + 1, col) ||
                         dfs(board, word, level + 1, row, col - 1) ||
                         dfs(board, word, level + 1, row, col + 1);
        board[row][col] = word.charAt(level);   // Remember to recovery the altered item on the board.
        return result;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s