1. 程式人生 > 其它 >leetcode-回溯-79. 單詞搜尋

leetcode-回溯-79. 單詞搜尋

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        int n = board[0].size();
        bool res = false;
        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(back(board, visited,word,i,j,0)) // 對首字母一樣的,開始遍歷 return true; } } return false; } bool back(vector<vector<char
>>& board, vector<vector<bool>> &visited, string word,int i, int j, int index){ int m = board.size(); int n = board[0].size(); if(i>=m||i<0||j>=n||j<0||visited[i][j]) return false; bool res; if(board[i][j]!=word[index])
return false; else{ visited[i][j]=true; //cout<<"i: "<<i<<" j: "<<j<<" "<<board[i][j]<<" ====index: "<<index<<endl; if(index==word.size()-1) return true; res = back(board,visited,word,i+1,j,index+1)||back(board,visited,word,i-1,j,index+1)||back(board,visited,word,i,j+1,index+1)||back(board,visited,word,i,j-1,index+1); visited[i][j] = false; } return res; } };