Saturday, February 8, 2014

Leetcode: WordSearch

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:

Using a backtracking algorithm, we could use an extra grid O($n^2$) to mark the used cells so far.
If we were ensured that a certain symbol would not appear in the grid, we could change the cells to mark that have been used, making the algorithm to use constant space. For instance, to pass the leetcode test, the symbol '$' was tried and it did work as shown in the following code.

public class Solution {
    public boolean exist(char[][] board, String word) {
        boolean sol = false;
        for(int i=0; i<board.length; i++)
        {
            for (int j=0; j<board[0].length; j++)
                sol = sol || exist(board, word, 0, i, j);
        }
        return sol;
    }
    
    public boolean exist(char[][] board, String word, int index, int row, int col)
    {
        if(board[row][col]!=word.charAt(index))
            return false;
        if(index == word.length()-1)
            return true;
        board[row][col] = '$';
        boolean val = false;
        if (row>0)
            val = val || exist(board, word, index+1, row-1, col);
        if (row<board.length-1)
            val = val || exist(board, word, index+1, row+1, col);
        if (col>0)
            val = val || exist(board, word, index+1, row, col-1);
        if (col<board[0].length-1)
            val = val || exist(board, word, index+1, row, col+1);
        board[row][col] = word.charAt(index);
        return val;
    }
}

No comments :

Post a Comment