Word Search

LeetCode #79


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 =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

Idea:

DFS + backtracking.

Code:

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {

        int m=board.size();
        int n=board[0].size();

        vector<vector<bool>> visited(m, vector<bool>(n, false));

        int len=word.size();

        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(findWord(board, i, j, 0, word, visited))
                    return true;
            }
        }

        return false;
    }

    bool findWord(vector<vector<char>>& board, int i, int j, int indx, string word, vector<vector<bool>>& visited){

        if(board[i][j]!=word[indx]) return false;

        int m=board.size();
        int n=board[0].size();
        int len=word.size();
        if(indx==len-1) return true;

        visited[i][j]=true; // good for now, mark as visited

        vector<pair<int, int>> move={{-1,0}, {0,1}, {1,0}, {0,-1}};

        bool existWord=false;
        for(auto e: move){
            int k=i+e.first;
            int l=j+e.second;

            if(k>=0 && k<m && l>=0 && l<n && !visited[k][l])
                existWord=existWord || findWord(board, k, l, indx+1, word, visited);
        }

        visited[i][j]=false; // Backtracking
        return existWord;


    }
};

results matching ""

    No results matching ""