笔试刷题BFS和DFS专题

BFS和DFS专题

  • LeetCode 77 组合(DFS)
  • LeetCode 104 树的最大深度(DFS)
  • LeetCode 111 二叉树的最小深度(DFS)
  • LeetCode 127 单词接龙(BFS)
  • LeetCode 207 课程表(拓扑排序BFS)
  • LeetCode 257 二叉树的所有路径
  • LeetCode 279 完全平方数(BFS)
  • LeetCode 130 被围绕的区域(DFS)
  • LeetCode 200 岛屿的数量(DFS)
  • LeetCode 542 01矩阵(BFS)
  • LeetCode 543 二叉树的直径(DFS)
  • LeetCode 733 图像渲染(DFS)
  • LeetCode 784 字母大小写全排列(DFS)

LeetCode 77 组合(DFS)

class Solution {
public:
    vector> ans;
    vector> combine(int n, int k) {
        vector path;
        dfs(n, k, 1, path);
        return ans;
    }
    void dfs(int n, int k, int t, vector path){
        if(!k){
            ans.push_back(path);
            return;
        } 
        for(int i = t; i <= n; i++){
            path.push_back(i); 
            dfs(n, k-1, i+1, path);
            path.pop_back();
        }  
    }
};

LeetCode 104 树的最大深度(DFS)

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

LeetCode 111 二叉树的最小深度(DFS)

 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        if(!left||!right) return left+right+1;
        return min(left, right)+1;
        
    }
};

LeetCode 127 单词接龙(BFS)

class Solution {
public:
    bool check(string a, string b)
    {
        int res = 0;
        for (int i = 0; i < a.size(); i ++ ) res += a[i] != b[i];
        return res == 1;
    }

    int ladderLength(string beginWord, string endWord, vector& wordList) {
        unordered_mapdist;
        queue que;
        que.push(beginWord), dist[beginWord] = 1;
        while (!que.empty())
        {
            string t = que.front();
            que.pop();

            if (t == endWord) return dist[t];
            for (auto &word : wordList)
                if (check(t, word) && !dist[word])
                {
                    dist[word] = dist[t] + 1;
                    que.push(word);
                }
        }
        return 0;
    }
};

LeetCode 207 课程表(拓扑排序BFS)

class Solution {
public:
    bool canFinish(int numCourses, vector>& prerequisites) {
        vector> graph(numCourses);
        vector in_degree(numCourses, 0);
        for (int i = 0; i < prerequisites.size(); i++) {
            in_degree[prerequisites[i].first]++;
            graph[prerequisites[i].second].push_back(prerequisites[i].first);
        }

        queue q;
        vector vis(numCourses, false);

        for (int i = 0; i < numCourses; i++)
            if (in_degree[i] == 0)
                q.push(i);
        while (!q.empty()) {
            int sta = q.front();
            q.pop();
            vis[sta] = true;
            for (int i = 0; i < graph[sta].size(); i++) {
                in_degree[graph[sta][i]]--;
                if (in_degree[graph[sta][i]] == 0)
                    q.push(graph[sta][i]);
            }
        }

        for (int i = 0; i < numCourses; i++)
            if (vis[i] == false)
                return false;
        return true;
    }
};

LeetCode 257 二叉树的所有路径

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector ans;
    vector binaryTreePaths(TreeNode* root) {
        string path;
        dfs(root, path);
        return ans;  
    }
    void dfs(TreeNode* root, string path){
        if(!root) return;
        if(!root->left && !root->right) {
            ans.push_back(path+to_string(root->val));
            return;
        }
        if(root->left) dfs(root->left, path+to_string(root->val)+"->");
        if(root->right) dfs(root->right, path+to_string(root->val)+"->");
    }  
};

LeetCode 279 完全平方数(BFS)

class Solution {
public:
    int numSquares(int n) {
        queue q;
        vector dist(n+1, -1);
        q.push(0);
        dist[0]=0;
        while (q.size()){
            int t = q.front();
            q.pop();
            if(t==n) return dist[t];
            for(int i = 1; i*i+t<=n; i++){
                int j = t+i*i;
                if(dist[j] == -1){
                    dist[j] = dist[t] + 1;
                    q.push(j);
                }
            }
        }
        return 0;
    }
};

LeetCode 130 被围绕的区域(DFS)

class Solution {
public:
    vector> st;
    int n, m;
    void solve(vector>& board) {
        if(board.empty() || board[0].empty()) return;
        n = board.size(), m = board[0].size();
        for(int i = 0; i temp;
            for(int j = 0; j>&board, int x, int y){
        st[x][y] = true;
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        for(int i = 0; i < 4; i++){
            int a = x + dx[i], b = y + dy[i];
            if(a >= 0 && a < n && b >= 0 && b < m && !st[a][b] && board[a][b] == 'O')
                dfs(board, a, b);  
        }  
    }
};

LeetCode 200 岛屿的数量(DFS)

class Solution {
public:
    int n, m;
    int numIslands(vector>& grid) {
        if(grid.empty() || grid[0].empty()) return 0;
        n = grid.size(), m = grid[0].size();
        int res = 0;
        for(int i = 0; i < n; i ++ ){
            for(int j = 0; j < m; j++){
                if(grid[i][j] == '1'){
                res++;
                dfs(grid,i,j);
                } 
            }  
        }
         return res;  
    }
    void dfs(vector>& grid, int x, int y){
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        grid[x][y] = '0';
        for(int i = 0; i < 4; i++){
            int a = x + dx[i], b = y + dy[i];
            if(a >= 0 && a < n && b >= 0 && b < m && grid[a][b] == '1')
                dfs(grid, a, b);
        }     
    }
};

LeetCode 542 01矩阵(BFS)

class Solution {
public:
    int dx[4] = {0, 1, 0, -1};
    int dy[4] = {1, 0, -1, 0};
    vector> updateMatrix(vector>& matrix) {
        int n = matrix.size(), m = matrix[0].size();
        queue> q;
        vector> dis(n, vector(m, -1));

        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                if (matrix[i][j] == 0) {
                    dis[i][j] = 0;
                    q.push(make_pair(i, j));
                }

        while (!q.empty()) {
            pair sta = q.front();
            q.pop();
            for (int i = 0; i < 4; i++) {
                int x = sta.first + dx[i], y = sta.second + dy[i];
                if (x < 0 || x >= n || y < 0 || y >= m || dis[x][y] != -1)
                    continue;

                dis[x][y] = dis[sta.first][sta.second] + 1;
                q.push(make_pair(x, y));
            }
        }

        return dis;
    }
};

LeetCode 543 二叉树的直径(DFS)

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
     int ans = 0;
     dfs(root, ans);
     return ans;
    }
    int dfs(TreeNode *r, int &ans){
        if(r == NULL) return -1;
        int d1 = dfs(r->left, ans);
        int d2 = dfs(r->right, ans);
        ans = max(ans, d1+d2+2);
        return max(d1, d2)+1;
    }
};

LeetCode 733 图像渲染(DFS)

class Solution {
public:
    vector> floodFill(vector>& image, int sr, int sc, int newColor) {
        if(image.empty()||image[0].empty()) return image;
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        int oldColor = image[sr][sc];
        if(oldColor == newColor) return image;
        image[sr][sc] = newColor;
        for(int i = 0; i<4; i++ ){
            int x = sr + dx[i], y = sc + dy[i];
            if(x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oldColor)
                floodFill(image, x, y, newColor);
        }
        return image;
    }
};

LeetCode 784 字母大小写全排列(DFS)

class Solution {
public:
    vector ans;
    vector letterCasePermutation(string S) {
        dfs(S, 0);
        return ans;
    }
    void dfs(string S, int t){
        if(t==S.size()) {
            ans.push_back(S); 
            return;   
        }  
        dfs(S, t+1);
        if(S[t]>='A'){
            S[t]^=32;
            dfs(S, t+1);
        }
    }
};

你可能感兴趣的:(算法笔试,算法与数据结构,C++,leetcode)