Word Search(Medium)


Problem description

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.

Example

Given board = 
[
    "ABCE",
    "SFCS",
    "ADEE"
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

Problem Link

This is an interview problem of Facebook.
Using backtracking.

My code:

class Solution {
public:
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    bool exist(vector<vector<char> > &board, string word) {
        // write your code here
        int n = board.size();
        int m = word.length();
        if (m == 0) return true;
        if (n == 0) return false;
        m = board[0].size();

        vector<vector<bool>> vis(n, vector<bool>(n, false));  
        for (int i = 0; i < n; ++ i) {
            for (int j = 0; j < m; ++ j) if (board[i][j] == word[0]) {
                vis[i][j] = true;
                if (dfs(i, j, 1, board, word, vis)) return true;
                vis[i][j] = false;
            }
        }
        return false;
    }

    int dx[4] = {1, -1, 0, 0};
    int dy[4] = {0, 0, 1, -1};
    bool dfs(int x, int y, int i, vector<vector<char>> &board, string &word, vector<vector<bool>> &vis) {
         int n = board.size();
         int m = word.length();
         if (i >= m) return true;
         m = board[0].size();

         for (int j = 0; j < 4; ++ j) {
             int xx = x + dx[j];
             int yy = y + dy[j];
             if (xx >= 0 && xx < n && yy >= 0 && yy < m && board[xx][yy] == word[i] && !vis[xx][yy]) {
                 vis[xx][yy] = true;
                 if (dfs(xx, yy, i + 1, board, word, vis)) return true;
                 vis[xx][yy] = false;
             } 
         }
         return false;
    }
};

results matching ""

    No results matching ""