Wednesday, September 17, 2014

[Leetcode] 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.


Analysis:


Do DFS for each matched first character. Note: don't forget to set visited flag for the char in board for BFS and DFS. using board[i][j] = '#' in the code.



bool helper(vector< vector< char> > &board, string word, int i, int j, int k)
{
    if (k == word.size())
        return true;
    else if (i <0 data-blogger-escaped-i="">= board.size() || j < 0 || j >= board[0].size() || board[i][j] != word[k])
        return false;
    else {
        //dfs, marked the cell as visited
        char tmp = board[i][j];
        board[i][j] = '#';
        if (helper(board, word, i + 1, j, k+1) ||
            helper(board, word, i, j+1, k+1) ||
            helper(board, word, i - 1, j, k+1) ||
            helper(board, word, i, j - 1, k+1))
            return true;
        board[i][j] = tmp;
    }
    return false;
}

bool exist(vector< vector< char> > &board, string word) {
    for(int i=0; i< board.size(); i++)
    {
        for(int j=0; j < board[i].size();j++)
        {
            if (board[i][j] == word[0] && helper(board, word, i, j, 0))
                return true;
        }
    }
    
    return false;
}

No comments:

Post a Comment