编程语言
首页 > 编程语言> > Leetcode---深度优先搜索(回溯算法)

Leetcode---深度优先搜索(回溯算法)

作者:互联网

1. 剑指 Offer II 116. 省份数量    

力扣

(这道题还可用BFS做。做法看BFS的例题整理)

class Solution {
public:
    void dfs(vector<vector<int>>& isConnected, int index, int size, vector<int>& visit) {
        for (int i = 0; i < size; ++i) {
            if (isConnected[index][i] == 1 && visit[i] == 0 ) {
                visit[i] = 1;
                dfs(isConnected, i, size, visit);
            }
        }
    }
    int findCircleNum(vector<vector<int>>& isConnected) {
        int size = isConnected.size();
        vector<int> visit(size, 0);
        int res = 0;
        for (int i = 0; i < size; ++i) {
            if (visit[i] == 0) {
                res++;
                dfs(isConnected, i, size, visit);
            }

        }
        return res;
    }
}; 

标签:int,res,visit,isConnected,---,vector,回溯,Leetcode,size
来源: https://blog.csdn.net/qq_34793133/article/details/121942742