【ING】dfs总结

https://leetcode.com/tag/depth-first-search/

https://leetcode.com/problems/longest-increasing-path-in-a-matrix/

class Solution {
    int dfs(vector>& matrix, vector > & visited, int x, int y) {
        if(visited[x][y] != -1)
            return visited[x][y];
        int res = 1;
        //left
        if(y > 0 && matrix[x][y-1] > matrix[x][y])
            res = max(res, dfs(matrix, visited, x, y-1) + 1) ;
        //right
        if(y < matrix[0].size() - 1 && matrix[x][y+1] > matrix[x][y])
            res = max(res, dfs(matrix, visited, x, y+1) + 1);
        //up
        if(x > 0 && matrix[x-1][y] > matrix[x][y])
            res = max(res, dfs(matrix, visited, x-1, y) + 1);
        //down
        if(x < matrix.size() - 1 && matrix[x+1][y] > matrix[x][y])
            res = max(res, dfs(matrix, visited, x+1, y) + 1);
        visited[x][y] = res;
        return res;
    }
public:
    int longestIncreasingPath(vector>& matrix) {
        int m = matrix.size();
        if(m == 0) return 0;
        int n = matrix[0].size();
        if(n == 0) return 0;
        
        vector > visited(m,vector(n, -1));
        
        int res = 0;
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++)
                res = max(res, dfs(matrix, visited, i, j));
        return res;
    }
};

https://leetcode.com/problems/maximum-depth-of-binary-tree/
递归版本:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL) return 0;
        return max(maxDepth(root->left),maxDepth(root->right)) + 1;
    }
};

非递归版本(bfs):

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL) return 0;
        queue nodeQueue;
        int res = 0;
        nodeQueue.push(root);
        while(!nodeQueue.empty()) {
            res++;
            int tmpsize= nodeQueue.size();
            for(int i = 0; i < tmpsize; i++) {
                TreeNode * temp = nodeQueue.front();
                nodeQueue.pop();
                //cout<<"res="<

你可能感兴趣的:(【ING】dfs总结)