Tuesday, October 29, 2013

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: DFS; we use a visited matrix to record the visited nodes.

class Solution {
public:
    bool searcher(vector<vector<char>> board, string word, int cur, vector<vector<bool>> &visited, int x, int y){
        if(board[x][y]!=word[cur])
            return false;
        if(cur==word.size()-1)
            return true;
        visited[x][y]=true;
        int m=board.size(), n=board[0].size();
        if(y-1>=0 && !visited[x][y-1] && searcher(board, word, cur+1, visited, x, y-1))
            return true;
        if(y+1<n && !visited[x][y+1] && searcher(board, word, cur+1, visited, x, y+1))
            return true;
        if(x-1>=0 && !visited[x-1][y] && searcher(board, word, cur+1, visited, x-1, y))
            return true;
        if(x+1<m && !visited[x+1][y] && searcher(board, word, cur+1, visited, x+1, y))
            return true;
        visited[x][y]=false;
        return false;
    }
    bool exist(vector<vector<char> > &board, string word) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(word.empty())
            return true;
        if(board.empty() || board[0].empty())
            return false;
        int m = board.size(), n = board[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(board[i][j]==word[0]){
                    if(searcher(board, word, 0, visited, i, j))
                        return true;
                }
            }
        }
        return false;
    }
};

No comments:

Post a Comment