Friday, June 19, 2015

Word Search | Leetcode

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

---

Solution: Create a boolean matrix "seen" to mark whether each cell has been seen or not. A recursive function will then check for each character, checking the boolean matrix to avoid double-using each cell, and then self-recurse. When we reach the end of the word successfully, then we have found a match.

To reuse the board to mark seen is not a good idea because we do not have to restrict the possible range of input characters, unless this has otherwise been explicitly called out. Though you probably can reuse the board to pass the leetcode judge.

public class Solution {
    public boolean exist(char[][] board, String word) {
        boolean[][] seen = new boolean[board.length][board[0].length];

        for (int y = 0; y < board.length; y++) {
            for (int x = 0; x < board[0].length; x++) {
                if (exists(board, seen, word, 0, y, x)) return true;
            }
        }
        return false;
    }
    
    private boolean exists(char[][] board, boolean[][] seen, String word, int start, int y, int x) {
        if (word.charAt(start) != board[y][x] || seen[y][x]) {
            return false;
        }
        
        if (start == word.length() - 1) return true;
        
        seen[y][x] = true;

        if (y > 0 && exists(board, seen, word, start + 1, y - 1, x)) {
            return true;
        }
        if (y < board.length - 1 && exists(board, seen, word, start + 1, y + 1, x)) {
            return true;
        }
        if (x > 0 && exists(board, seen, word, start + 1, y, x - 1)) {
            return true;
        }
        if (x < board[0].length - 1 && exists(board, seen, word, start + 1, y, x + 1)) {
            return true;
        }
        
        seen[y][x] = false;
        
        return false;
    }
}

No comments: