zoukankan      html  css  js  c++  java
  • leetcode 79 单词搜索

    简介

    回溯

    code

    class Solution {
    public:
        int n;
        int m;
        bool find;
        void dfs(vector<vector<char>>& board, vector<vector<bool>>& visited, string &word, int index, int i, int j){
            if(index == word.size()){
                find = true;
                return;
            }
            if(i >= n) return;
            if(i < 0) return;
            if(j >= m) return;
            if(j < 0) return;
            if(board[i][j] == word[index]){
                if(visited[i][j] == false) {
                    visited[i][j] = true;
                    dfs(board, visited, word, index+1, i, j+1);
                    visited[i][j] = false;
    
                    visited[i][j] = true;
                    dfs(board, visited, word, index+1, i, j-1);
                    visited[i][j] = false;
    
                    visited[i][j] = true;
                    dfs(board, visited, word, index+1, i+1, j);
                    visited[i][j] = false;
    
                    visited[i][j] = true;
                    dfs(board, visited, word, index+1, i-1, j);
                    visited[i][j] = false;
                }
            }else{
                return;
            }
        }
        bool exist(vector<vector<char>>& board, string word) {
            n = board.size();
            m = board[0].size();
            int index = 0;
            vector<vector<bool>> visited(n, vector<bool>(m, false));
            find = false;
            for(int i=0; i<n; i++){
                for(int j=0; j<m; j++){
                    dfs(board, visited, word, 0, i, j);
                    if(find) return true;
                }
            }
            return false;
    
        }
    };
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    软工总结博客
    第四次个人博客
    第三次博客作业
    结对项目作业
    第二次博客作业
    个人博客作业_week14
    个人博客作业_week7
    结对编程_附加题_博客2
    结对编程1_四则运算器_博客1
    个人博客作业_week3
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14842882.html
Copyright © 2011-2022 走看看