79. Word Search (dfs)

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:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

 

class Solution:
    def __init__(self):
        self.res = False
    
    def exist(self, board: List[List[str]], word: str) -> bool:

        def dfs(i, j, index):
            # Check if current position is out of bounds or current character does not match
            if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]) or board[i][j] != word[index]:
                return False
            
            # If the entire word has been found
            if index == len(word) - 1:
                return True
            
            # Mark current position as visited
            temp = board[i][j]
            board[i][j] = '#'
            
            # Check neighboring cells
            found = (dfs(i + 1, j, index + 1) or
                     dfs(i - 1, j, index + 1) or
                     dfs(i, j + 1, index + 1) or
                     dfs(i, j - 1, index + 1))
            
            # Restore current position
            board[i][j] = temp
            
            return found
        
        for i in range(len(board)):
            for j in range(len(board[0])):
                if dfs(i, j, 0):
                    return True
                
        return False

 

 

 

 

class Solution {
public:
    bool dfs(vector<vector<char>>& board, int i, int j, int level,string wanted_word) {
        if (level == wanted_word.size()) {
            return true;
        }
        if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size()) {
            return false;
        }
        if (board[i][j] != wanted_word[level]) {
            return false;
        }
        char t = board[i][j];
        board[i][j] = '0';
        bool res = (
                dfs(board,i-1,j,level+1,wanted_word) || 
                dfs(board,i+1,j,level+1,wanted_word) ||
                dfs(board,i,j+1,level+1,wanted_word) ||
                dfs(board,i,j-1,level+1,wanted_word));
        board[i][j] = t;
        return res;
    }
    bool exist(vector<vector<char>>& board, string word) {
        for(int i = 0; i < board.size();i++) {
            for(int j = 0; j < board[0].size();j++) {
                if (dfs(board,i,j,0,word)) return true;
            }
        }
        return false;
    }
};

 

 

 1 class Solution {
 2 public:
 3     bool exist(vector<vector<char>>& board, string word) {
 4         for(int i = 0;i < board.size();i++){
 5             for(int j =0;j<board[0].size();j++){
 6                 bool res = dfs(board,i,j,word,0);
 7                 if(res) return true;
 8             }
 9         }
10         return false;
11     }
12     bool dfs(vector<vector<char>>& board, int i,int j,string word,int cur_len){
13         if(cur_len>=word.size()) return true;
14         if(i<0||j<0||i>=board.size()||j>=board[0].size()) return false;
15         if(board[i][j]==word[cur_len]){
16             char c = board[i][j];
17             board[i][j]='+';
18             bool res = dfs(board,i,j-1,word,cur_len+1)||
19                        dfs(board,i-1,j,word,cur_len+1)||
20                       dfs(board,i+1,j,word,cur_len+1)||   
21                       dfs(board,i,j+1,word,cur_len+1);
22             board[i][j] = c;
23             return res;
24         }
25         else
26             return false;
27     }
28 };

 

posted @ 2019-01-09 10:18  乐乐章  阅读(145)  评论(0编辑  收藏  举报