DFS搜索题目,修改状态,然后恢复状态

    时间复杂度:Leetcode 79. 单词搜索 - 图1 其中Leetcode 79. 单词搜索 - 图2为字符串的长度。

    1. class Solution {
    2. public:
    3. int dx[4] = {-1,1,0,0}, dy[4] = {0,0,-1,1};
    4. int m,n;
    5. bool exist(vector<vector<char>>& board, string word) {
    6. if(board.size()==0||board[0].size()==0) return false;
    7. m = board.size(), n = board[0].size();
    8. for(int i=0;i<m;i++){
    9. for(int j=0;j<n;j++){
    10. if(dfs(board,i,j,word,0)) return true;
    11. }
    12. }
    13. return false;
    14. }
    15. bool dfs(vector<vector<char>>&board,int x,int y,string word,int u){
    16. if(board[x][y]!=word[u]) return false;
    17. if(u==word.size()-1) return true;
    18. board[x][y] = '.'; // 修改
    19. for(int i=0;i<4;i++){
    20. int xx = x+dx[i], yy = y+dy[i];
    21. if(xx>=0&&xx<m&&yy>=0&&yy<n&&dfs(board,xx,yy,word,u+1)) return true;
    22. }
    23. board[x][y] = word[u]; //恢复
    24. return false;
    25. }
    26. };