Guys i was trying to think the intutition behind the recursion of graph dfs traversal , lets take a LC question "Number of provnices"https://leetcode.com/problems/number-of-provinces/ for example , where the solution of the problem is just to find the number of components in the graph (Complete code below).
Now if we see in the dfs function we have to eventually visit very node in the particular component .
for that if i think using PMI thought process , i can do the this work (visiting ) for a single node and handle the rest(subproblem) of work(visiting node) to the recursion ,its making sense since in the code we are using a for loop in dfs function ,But what about the base condition of this recursion ?? Where the hell it is??
There is no base condition as you can see in the code !!!! .
Is it because after after the sub problem work my toatal work is finished and i dont need any condition?
Guys please someone explain this in the comment .
Solution credits: Alexander https://leetcode.com/alexander/
class Solution {
public:
int findCircleNum(vector<vector<int>>& M) {
if (M.empty()) return 0;
int n = M.size();
vector<bool> visited(n, false);
int groups = 0;
for (int i = 0; i < visited.size(); i++) {
groups += !visited[i] ? dfs(i, M, visited), 1 : 0;
}
return groups;
}
private:
void dfs(int i, vector<vector<int>>& M, vector<bool>& visited) {
visited[i] = true;
for (int j = 0; j < visited.size(); j++) {
if (i != j && M[i][j] && !visited[j]) {
dfs(j, M, visited);
}
}
}
};