1 -- 2 4 6 7
| |
3 5
___
Cealing of {1,2,3} = \/ 3 = 2.23 = rounded off 3
__
Cealing of {4,5} = \/ 2 = 1.41 = rounded off 2
Cealing of 6 = 1
Cealing of 7 = 1
Answer: 7Find Connected components, Find sqrt.
class Solution {
using vec = vector<int>;
using vecB = vector<bool>;
using vecVec = vector<vec>;
stack<int> st;
void dfs(vecVec& adjList, vecB& visited, int start) { //4
st.push(start);
while (st.empty() != 1) {
int top = st.top(); st.pop();
visited[top] = true;
//Find neighbour
for (int i = 0; i < adjList[top].size(); ++i) {
if (!visited[adjList[top][i]]) {
st.push(adjList[top][i]);
}
}
}
}
public:
int countComponents(int n, vecVec& edges) {
if (!n)
return n;
int connectedComp = 0;
vecB visited(n, 0); //2
vecVec adjList(n);
for (int i = 0; i < edges.size(); ++i) { //1
adjList[edges[i][0]].push_back(edges[i][1]);
adjList[edges[i][1]].push_back(edges[i][0]);
}
//If any unvisited node, Perform DFS
for (int i = 0; i < n; ++i) { //3
if (!visited[i]) {
dfs(adjList, visited, i);
connectedComp++; //4
}
}
return connectedComp;
}
}
int main()
{
Solution o;
//vector<vector<int>> v = { {0, 1},{1, 2},{3, 4} }; cout << o.countComponents(5, v);
vector<vector<int>> v = { {0,1},{1,2},{2,3},{3,4} }; cout << o.countComponents(5, v);
}class Solution {
public:
stack<int> m_st;
void dfs(vector<vector<int>>& isConnected,
vector<bool>& vecVisited,
int start) {
m_st.push(start);
while (!m_st.empty()) {
int top = m_st.top();
m_st.pop();
vecVisited[top] = true;
//Find Neighbour
for (int i = 0; i < isConnected[top].size(); ++i) {
//Except myself check all neighbours
//if any unvisited neighbour, push in stack
if (i != top) {
if (isConnected[top][i] == 1 && !vecVisited[i])
m_st.push(i);
}
}
}
}
public:
int findCircleNum(vector<vector<int>>& isConnected) {
if (!isConnected.size())
return 0;
int rows = isConnected.size();
int iConnected = 0;
vector<bool> vecVisited(rows, false);
stack<int> s;
for (int i = 0; i < rows; ++i) {
if (!vecVisited[i]) {
dfs(isConnected, vecVisited, i);
iConnected++;
}
}
return iConnected;
}
};