Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //https://leetcode.com/problems/word-search/
- class Solution {
- public:
- 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]) {
- std::vector<std::vector<bool>> visited_array(board.size(), std::vector<bool>(board[0].size(), false));
- bool word_exists = exists(board, visited_array, i,j, word, 0);
- if(word_exists)
- return true;
- }
- }
- }
- return false;
- }
- private:
- bool exists(std::vector<std::vector<char>> &board, std::vector<std::vector<bool>> & visited_array, int r, int c, std::string & word, int current_index) {
- if(current_index == word.size())
- return true;
- if(r < 0 || r >= board.size())
- return false;
- if(c <0 || c >= board[0].size())
- return false;
- if(board[r][c] == word[current_index] && visited_array[r][c] == false) {
- visited_array[r][c] = true;
- bool is_whole_word_present = exists(board, visited_array, r+1,c, word, current_index+1) ||
- exists(board, visited_array, r,c+1, word, current_index+1) ||
- exists(board, visited_array, r-1,c, word, current_index+1) ||
- exists(board, visited_array, r,c-1, word, current_index+1);
- if(is_whole_word_present)
- return true;
- visited_array[r][c] = false;
- }
- return false;
- }
- };
Add Comment
Please, Sign In to add comment