https://leetcode.com/problems/friend-circles/description/
int findCircleNum(vector<vector<int>>& M) {
int m = M.size();
int res = 0;
vector<bool> v(m, true);
for(int i=0; i<m; i++){
if(v[i]) {
res++;
stack<int> st;
st.push(i);
v[i] = false;
while(!st.empty()) {
int k = st.top();
st.pop();
for(int j=0; j<m; j++) {
if(v[j] && M[k][j]) {
v[j] = false;
st.push(j);
}
}
}
}
}
return res;
}
or DFS,
void dfs(vector<vector<int>>& M, vector<bool>& visited, int i) {
visited[i] = true;
for(int j=0; j<visited.size(); j++) {
if(i!=j && M[i][j] && !visited[j]) dfs(M, visited, j);
}
}
int findCircleNum(vector<vector<int>>& M) {
int m = M.size();
int res = 0;
vector<bool> visited(m, false);
for(int i=0; i<m; i++) {
if(!visited[i]) {
dfs(M, visited, i);
res++;
}
}
return res;
}
No comments:
Post a Comment