1
0
mirror of https://github.com/opencv/opencv_contrib.git synced 2025-10-16 22:35:51 +08:00

Merge pull request #3207 from aimbot6120:swtfix

replaced recursion DFS to stack DFS
This commit is contained in:
Pranay Pandit
2022-04-02 03:44:58 +05:30
committed by GitHub
parent fe43396536
commit da967e070e

View File

@@ -7,6 +7,7 @@
#include <unordered_map> #include <unordered_map>
#include <limits> #include <limits>
#include <stack>
using namespace std; using namespace std;
@@ -91,15 +92,25 @@ void addEdge(std::vector< std::vector<int> >& adj, int u, int v)
static static
void DFSUtil(int v, std::vector<bool> & visited, std::vector< std::vector<int> >& adj, int label, std::vector<int> &component_id) void DFSUtil(int v, std::vector<bool> & visited, std::vector< std::vector<int> >& adj, int label, std::vector<int> &component_id)
{ {
// Mark the current node as visited and label it as belonging to the current component stack<int> s;
visited[v] = true; s.push(v);
component_id[v] = label; while(!s.empty()){
// Recur for all the vertices v = s.top();
// adjacent to this vertex s.pop();
for (size_t i = 0; i < adj[v].size(); i++) { if(!visited[v])
int neighbour = adj[v][i]; {
if (!visited[neighbour]) { // Mark the current node as visited and label it as belonging to the current component
DFSUtil(neighbour, visited, adj, label, component_id); visited[v] = true;
component_id[v] = label;
// Recur for all the vertices
// adjacent to this vertex
for (size_t i = 0; i < adj[v].size(); i++) {
int neighbour = adj[v][i];
if(!visited[neighbour])
{
s.push(neighbour);
}
}
} }
} }
} }