bool CircleFlowAlgorithm::reflow(DirectedGraph& g,const Rectangle<int>& area,
                                 ObjController& objController, float /*deltaTime*/)
{
    const int offsetX = area.getX();
    const int offsetY = area.getY();
    const int width = area.getWidth();
    const int height = area.getHeight();

    float interval = 2 * M_PI / (float) g.size();
    int cx = width/2;
    int cy = height/2;
//    float vl = cx - (2 * g->getNode(0)->r1) - 10;
    float vl = cx - 100;
    for (int a = 0; a < g.size(); ++a)
    {
        Point<int> nc = GraphUtils::rotateCoordinate(vl, 0, (float) a * interval);
        nc.x += offsetX;
        nc.y += offsetY;
        if(ObjectComponent* oc = objController.getObjectForId(g.getNode(a)->getLabel()))
        {
            Point<int> p(cx + nc.x*0.8, cy + nc.y*0.8);
            oc->setPosition(p, false);
        }
    }
    return false;
}
Exemple #2
0
size_t DirectedGraph<T, MASK>::scc(std::vector<size_t>* vertex_color) const {
	const DirectedGraph<T, MASK> rev_graph = reversed();
	std::vector<size_t> order(this->vertices_count_);
	top_sort_rec(&order);
	std::vector<bool> used(this->vertices_count_, false);
	std::vector<size_t> color(this->vertices_count_);
	Queue<size_t> queue(this->vertices_count_);
	size_t components_count = 0;
	for (const auto& v : order) {
		if (!used[v]) {
			queue.clear();
			queue.push(v);
			while (!queue.empty()) {
				const size_t vertex = queue.pop_front();
				color[vertex] = components_count;
				used[vertex] = true;
				for (const auto& it : rev_graph.edges(vertex)) {
					const size_t to = it.to();
					if (!used[to]) {
						used[to] = true;
						queue.push(to);
					}
				}
			}
			++components_count;
		}
	}
	if (vertex_color != nullptr) {
		vertex_color->swap(color);
	}
	return components_count;
}
bool ForceDirectedFlowAlgorithm::reflow(DirectedGraph& g,
                                        const Rectangle<int>& area,
                                        ObjController& objController,
                                        float /*deltaTime*/)
{
    // const Array<Node*>& nodes = g.getNodes();
    // const Array<Array<bool>>& edges = g.edges;

    Point<float> totalEnergy(0.0, 0.0);


    for (tNodesAndEdges& group : g.getConnectedGroups())
    {
        applyForces(totalEnergy, group, area.getWidth(), area.getHeight(), objController);
    }


    float lenTotalEnergy = sqrt(totalEnergy.x * totalEnergy.x + totalEnergy.y * totalEnergy.y);

    // DBG(lenTotalEnergy);

    if (lenTotalEnergy < stopEnergy)
    {
        g.setPositions();
        return false;
    }

    return true;
}
Exemple #4
0
vector<Component> FindZeroIndegreeComponents(const DirectedGraph &graph) {
  vector<Component> components = FindWeaklyConnectedComponents(graph);
  vector<bool> top_component_flags(components.size(), true);
  vector<int> vertices_components(graph.size());
  for (int component_number = 0; 
       component_number < components.size(); ++component_number) {
    for (int vertex : components[component_number]) {
      vertices_components[vertex] = component_number;
    }
  }
  for (int vertex = 0; vertex < graph.size(); ++vertex) {
    for (int adj_vertex : graph.GetAdjacentVertices(vertex)) {
      if (vertices_components[vertex] != vertices_components[adj_vertex]) {
        top_component_flags[vertices_components[adj_vertex]] = false;
      }
    }
  }
  vector<Component> top_components;
  for (int component_number = 0; 
       component_number < components.size(); ++component_number) {
    if (top_component_flags[component_number]) {
      top_components.push_back(components[component_number]);
    }
  }
  return top_components;
}
/**
 * randomly generate a graph, for test purpose
 */
DirectedGraph * randgraph(int nvertex) 
{
	DirectedGraph * g = new DirectedGraph;
	int i;	
	
	for(i=0;i<nvertex;i++) {
		g->add_vertex(i);
	}

	// random connect
	for(i=0;i<nvertex;i++) {
		int j;
		for(j=0;j<nvertex;j++) {
			if (i == j)
				continue;
			int dice = rand()%2;
			if (dice == 0) { 
				int w = rand()%100;
				g->add_edge(i, j, w);
			}
		}
	}

	
	return g;
}
Exemple #6
0
int main()
{
	using namespace alg;
	srand(time(NULL));
	DirectedGraph * g = new DirectedGraph;
	// construct 3 islands
	int32_t i;
	for (i=0;i<9;i++) {
		g->add_vertex(i);
	}

	g->add_edge(0,1,1);
	g->add_edge(1,2,1);
	g->add_edge(2,0,1);

	g->add_edge(3,4,1);
	g->add_edge(4,5,1);
	g->add_edge(5,3,1);

	g->add_edge(6,7,1);
	g->add_edge(7,8,1);
	g->add_edge(8,6,1);

	// connect island
	g->add_edge(0,3,1);
	g->add_edge(3,8,1);

	g->printdot();

	printf("find strongly connected component\n");
	SCC(*g);

	delete g;
	return 0;
}
int main(void)
{
	using namespace alg;
	srand(time(NULL));
	int NVERTEX = 6;
	DirectedGraph * g = randgraph(NVERTEX);
	g->print();

	printf("finding Maximal Flow from 0 to 5: \n");	
	EdmondsKarp ek(*g);
	uint32_t maxflow = ek.run(0,5);

	printf("Max Flow is %d\n", maxflow);
	printf("the residual network\n");
	printf("\t");
	for(uint32_t i=0;i<g->vertex_count();i++) {
		printf("%d\t", ek.rmap()[i]);
	}
	printf("\n");

	for(uint32_t i=0;i<g->vertex_count();i++) {
		printf("%d\t",ek.rmap()[i]);
		for(uint32_t j=0;j<g->vertex_count();j++) {
			printf("%d\t", ek.residual()(i,j));
		}
		printf("\n");
	}

	delete g;

	return 0;
}
Exemple #8
0
int GetMaxCompanySize(const DirectedGraph &graph) {
  vector<Component> top_components = FindZeroIndegreeComponents(graph);
  int min_size = graph.size() + 2;
  for (const Component &top_component : top_components) {
    min_size = std::min(min_size, static_cast<int>(top_component.size()));
  }
  return graph.size() + 1 - min_size;
};
Exemple #9
0
DirectedGraph<T, MASK> DirectedGraph<T, MASK>::reversed() const {
	DirectedGraph<T, MASK> result;
	result.init(this->vertices_count_);
	for (const auto& edge : this->edges()) {
		result.add_directed_edge(edge.reversed());
	}
	return result;
}
Exemple #10
0
DirectedGraph Transpose(const DirectedGraph &graph) {
  DirectedGraph tr_graph = DirectedGraph(graph.size());
  for (int vertex = 0; vertex < graph.size(); ++vertex) {
    for (int adj_vertex : graph.GetAdjacentVertices(vertex)) {
      tr_graph.AddEdge(Edge(adj_vertex, vertex));
    }
  }
  return tr_graph;
}
Exemple #11
0
 bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
     // 本质上,相当于判断有向图中是否有环
     // 如果有环,则不能完成所有课程
     
     // corner case
     if (numCourses <= 0) return true;
     
     // build the graph
     DirectedGraph graph = buildGraph(numCourses, prerequisites);
     
     // detect cycle
     return !graph.detectCycle();
 }
/*
 *   (0)________>(2)
 *    |         /   \
 *    |        /     \
 *   (5)----(3)-----(4)
 */
TEST(DirectedBreadthFirstPathSearch, pathTo) {
    DirectedGraph graph {20};
    graph.addEdge(0, 2);
    graph.addEdge(2, 3);
    graph.addEdge(2, 4);
    graph.addEdge(3, 5);
    graph.addEdge(0, 5);
    const DirectedBreadthFirstPathSearch search (&graph, 0);
    Iterator<int>* it = search.pathTo(5);
    EXPECT_EQ(0, it->next());
    EXPECT_EQ(5, it->next());
    EXPECT_EQ(false, it->hasNext());
}
static ext::optional<std::vector<pbxspec::PBX::FileType::shared_ptr>>
SortedFileTypes(std::vector<pbxspec::PBX::FileType::shared_ptr> const &fileTypes)
{
    DirectedGraph<pbxspec::PBX::FileType::shared_ptr> graph;

    for (pbxspec::PBX::FileType::shared_ptr const &fileType : fileTypes) {
        if (fileType->base() != nullptr) {
            graph.insert(fileType->base(), { fileType });
        }
        graph.insert(fileType, { });
    }

    return graph.ordered();
}
cv::Mat GraphComparator::_paintGraph(shared_ptr<OsmMap> map, DirectedGraph& graph, ShortestPath& sp)
{
  const WayMap& ways = map->getWays();

  cv::Mat mat(cvSize(_width, _height), CV_32FC1);

  for (int y = 0; y < _height; y++)
  {
    float* row = mat.ptr<float>(y);
    for (int x = 0; x < _width; x++)
    {
      row[x] = -1.0;
    }
  }

  for (WayMap::const_iterator it = ways.begin(); it != ways.end(); ++it)
  {
    shared_ptr<Way> w = it->second;
    double cost = sp.getNodeCost(w->getNodeIds()[0]);
    if (cost >= 0)
    {
      double friction = graph.determineCost(w);
      if (friction >= 0)
      {
        double startCost = cost;
        double endCost = sp.getNodeCost(w->getNodeIds()[w->getNodeCount() - 1]);
        _paintWay(mat, map, w, friction, startCost, endCost);
        _maxGraphCost = std::max(startCost, endCost);
      }
    }
  }

  return mat;
}
static void DumpEdgeList(DirectedGraph<Layer*>& aGraph)
{
  nsTArray<DirectedGraph<Layer*>::Edge> edges = aGraph.GetEdgeList();
  
  for (PRUint32 i = 0; i < edges.Length(); i++) {
    fprintf(stderr, "From: %p, To: %p\n", edges.ElementAt(i).mFrom, edges.ElementAt(i).mTo);
  }
}
Exemple #16
0
	/*
	Method:
	1. calculate the topological order of the directed graph, t[]
	2. calculate the ealiest event time of each vertice, ee[]
	3. return ee[t[N-1]], N is the number of vertices
	*/
	int AOEnetwork::minCost(const DirectedGraph & g)const
	{
		Topologic obj;
		size_t * t = obj.order(g);
		int * ee = ealiestEventTime(g, t);
		int cost = ee[t[g.numberOfVertices() - 1]];
		delete[]t;
		delete[]ee;
		return cost;
	}
Exemple #17
0
void DepthFirstSearch(const DirectedGraph &graph, vector<int> &order, 
         vector<bool> &visited, int vertex) {
  visited[vertex] = true;
  for (int outgoing_vertex : graph.GetAdjacentVertices(vertex)) {
    if (!visited[outgoing_vertex]) {
      DepthFirstSearch(graph, order, visited, outgoing_vertex);
    }
  }
  order.push_back(vertex);
}
Exemple #18
0
static void DumpEdgeList(DirectedGraph<Layer*>& aGraph)
{
  const nsTArray<DirectedGraph<Layer*>::Edge>& edges = aGraph.GetEdgeList();
  
  for (uint32_t i = 0; i < edges.Length(); i++) {
    fprintf(stderr, "From: ");
    print_layer(stderr, edges.ElementAt(i).mFrom);
    fprintf(stderr, ", To: ");
    print_layer(stderr, edges.ElementAt(i).mTo);
    fprintf(stderr, "\n");
  }
}
int main()
{
	srand(time(NULL));
	int NVERTEX = 20;
	DirectedGraph * g = randgraph(NVERTEX);
	g->print();

	printf("Random Delete Vertex:\n");
	// random delete vertex 
	int i;
	for(i=0;i<NVERTEX;i++) {
		int n = rand()%NVERTEX;	
		printf("delete: %d\n", n);
		g->delete_vertex(n);
	}

	g->print();
	printf("Delete All Edges: \n");
	
	for(i=0;i<NVERTEX;i++) {
		int j;
		for(j=i+1;j<NVERTEX;j++) {
			g->delete_edge(i, j);
		}
	}

	g->print();
	return 0;
}
Exemple #20
0
vector<Component> FindWeaklyConnectedComponents(const DirectedGraph &graph) {
  const DirectedGraph tr_graph = Transpose(graph);
  vector<bool> visited(graph.size(), false);
  vector<int> order;
  Component current_component;
  vector<Component> components;
  for (int vertex = 0; vertex < graph.size(); ++vertex) {
    if (!visited[vertex])
      DepthFirstSearch(graph, order, visited, vertex);
    if (order.size() == graph.size())
      break;
  }
  visited.assign(graph.size(), false);
  for (auto it = order.rbegin(); it != order.rend(); ++it) {
    if (!visited[*it]) {
      DepthFirstSearch(tr_graph, current_component, visited, *it);
      components.push_back(current_component);
      current_component.clear();
    }
  }
  return components;
}
int main(void)
{
	using namespace alg;
	srand(time(NULL));
	int NVERTEX = 300;

	clock_t ek_start, ek_end, pr_start, pr_end;

	DirectedGraph * g = randgraph(NVERTEX);
//	g->print();

	printf("finding Maximal Flow from 0 to %d: \n", NVERTEX-1);
	printf("The graph containing %d edges.\n", g->edge_count());

	ek_start = clock();
	EdmondsKarp ek(*g);
	uint32_t maxflow = ek.run(0, NVERTEX-1);
	ek_end = clock();

	printf("Max Flow calculated by edmonds-karp algorithm is %d\n", maxflow);
//	printf("the residual network\n");
//	printf("\t");
//	for(uint32_t i=0;i<g->vertex_count();i++) {
//		printf("%d\t", ek2.rmap()[i]);
//	}
//	printf("\n");

//	for(uint32_t i=0;i<g->vertex_count();i++) {
//		printf("%d\t",ek2.rmap()[i]);
//		for(uint32_t j=0;j<g->vertex_count();j++) {
//			printf("%d\t", ek2.residual()(i,j));
//		}
//		printf("\n");
//	}
	
	pr_start = clock();
	RelabelToFront pr2(*g);
	uint32_t maxflow_pr = pr2.run(0, NVERTEX-1);
	pr_end = clock();

	printf("Max Flow calculated by push-relabel is %d\n", maxflow_pr);
//	printf("the residual and preflow network\n");
//	printf("\t");
//	for(uint32_t i=0; i<g->vertex_count(); i++) {
//		 printf("%d\t", pr2.rmap()[i]);
//	}
//	printf("\n");

//	for (uint32_t i=0; i<g->vertex_count(); i++){
//		printf("%d\t", pr2.rmap()[i]);
//		for (uint32_t j=0; j<g->vertex_count(); j++){
//			printf("%d\t", pr2.residual()(i,j));
//		}
//		printf("\n");
//	}
//	printf("\n");

	long ek_time = ek_end - ek_start;
	long pr_time = pr_end - pr_start;
	
	printf("The number of clock tick consumed by edmonds-karp is %ld\n", ek_time);
	printf("--------------------------------- by push-relabel is %ld\n", pr_time);
	
	delete g;

	return 0;
}
Exemple #22
0
int main(){    
    DirectedGraph<int> g;
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(3, 3);
    if(cycleCheck(&g))cout<<"cyclic graph"<<endl;
    else cout<<"acyclic graph"<<endl;
    
    /*Create minimum spanning tree of unweighted graph
    Graph<int> g;
    g.addEdge(1, 0);
    g.addEdge(0, 2);
    g.addEdge(2, 1);
    g.addEdge(0, 3);
    g.addEdge(3, 4);
    minimumSpanningTree(&g);*/
    
    /* Find shortest path between two vertices
    Graph<int> g;
    g.addEdge(1, 0);
    g.addEdge(0, 2);
    g.addEdge(2, 1);
    g.addEdge(0, 3);
    g.addEdge(3, 4);
    shortestPath(&g, 1, 3);
    */
    
    /* Check if graph is bipartite
    Graph<int> g;
    g.addEdge(0,1);
    g.addEdge(1,2);
    g.addEdge(0,2);
    if(isBipartiteBFS(&g))cout<<"Bipartite"<<endl;
    else cout<<"Not bipartite"<<endl;
    if(isBipartiteDFS(&g))cout<<"Bipartite"<<endl;
    else cout<<"Not bipartite"<<endl;*/
    
    /* Print reverse topological order
    DirectedGraph<int> g;
    g.addEdge(5, 2);
    g.addEdge(5, 0);
    g.addEdge(4, 0);
    g.addEdge(4, 1);
    g.addEdge(2, 3);
    g.addEdge(3, 1);
    g.print();
    topologicalSort(&g);
    */
    /* Find path between two vertices
    Graph<int> g1;
    g1.addEdge(1, 0);
    g1.addEdge(0, 2);
    g1.addEdge(2, 0);
    g1.addEdge(0, 3);
    g1.addEdge(3, 4);
    
    Graph<int> g2;
    g2.addEdge(0, 1);
    g2.addEdge(1, 2);
    
    findPathDFS(&g1, 0, 4);
    */
    
    //check cycle in graph using DFS
    /*if(cycleCheckBFS(&g1))cout<<"Cycle is present"<<endl;
    else cout<<"Cycle is not present"<<endl;*/
    
    /*if(cycleCheckBFS(&g2))cout<<"Cycle is present"<<endl;
    else cout<<"Cycle is not present"<<endl;*/
 
    //check cycle in graph using DFS
    /*if(cycleCheckDFS(&g1))cout<<"Cycle is present"<<endl;
    else cout<<"Cycle is not present"<<endl;
    
    if(cycleCheckDFS(&g2))cout<<"Cycle is present"<<endl;
    else cout<<"Cycle is not present"<<endl;*/
 
    /*
    Graph<int> g;
    g.addEdge( 0, 1);
    g.addEdge( 0, 4);
    g.addEdge( 1, 2);
    g.addEdge( 1, 3);
    g.addEdge( 1, 4);
    g.addEdge( 2, 3);
    g.addEdge( 3, 4);
    */
    
    //Depth First Search
    //depthFirstSearch(&g);
    //cout<<endl;
    
    //Breadth First Search
    //breadthFirstSearch(&g);
    //cout<<endl;
    
    // Print graph line by line such that each line contains node and all of its neighbours
    //g.print();
     
    return 0;
}
Exemple #23
0
void SortLayersBy3DZOrder(nsTArray<Layer*>& aLayers)
{
  uint32_t nodeCount = aLayers.Length();
  if (nodeCount > MAX_SORTABLE_LAYERS) {
    return;
  }
  DirectedGraph<Layer*> graph;

#ifdef DEBUG
  if (gDumpLayerSortList) {
    for (uint32_t i = 0; i < nodeCount; i++) {
      if (aLayers.ElementAt(i)->GetDebugColorIndex() == 0) {
        aLayers.ElementAt(i)->SetDebugColorIndex(gColorIndex++);
        if (gColorIndex > 7) {
          gColorIndex = 1;
        }
      }
    }
    fprintf(stderr, " --- Layers before sorting: --- \n");
    DumpLayerList(aLayers);
  }
#endif

  // Iterate layers and determine edges.
  for (uint32_t i = 0; i < nodeCount; i++) {
    for (uint32_t j = i + 1; j < nodeCount; j++) {
      Layer* a = aLayers.ElementAt(i);
      Layer* b = aLayers.ElementAt(j);
      LayerSortOrder order = CompareDepth(a, b);
      if (order == ABeforeB) {
        graph.AddEdge(a, b);
      } else if (order == BBeforeA) {
        graph.AddEdge(b, a);
      }
    }
  }

#ifdef DEBUG
  if (gDumpLayerSortList) {
    fprintf(stderr, " --- Edge List: --- \n");
    DumpEdgeList(graph);
  }
#endif

  // Build a new array using the graph.
  nsTArray<Layer*> noIncoming;
  nsTArray<Layer*> sortedList;

  // Make a list of all layers with no incoming edges.
  noIncoming.AppendElements(aLayers);
  const nsTArray<DirectedGraph<Layer*>::Edge>& edges = graph.GetEdgeList();
  for (uint32_t i = 0; i < edges.Length(); i++) {
    noIncoming.RemoveElement(edges.ElementAt(i).mTo);
  }

  // Move each item without incoming edges into the sorted list,
  // and remove edges from it.
  do {
    if (!noIncoming.IsEmpty()) {
      uint32_t last = noIncoming.Length() - 1;

      Layer* layer = noIncoming.ElementAt(last);
      MOZ_ASSERT(layer); // don't let null layer pointers sneak into sortedList

      noIncoming.RemoveElementAt(last);
      sortedList.AppendElement(layer);

      nsTArray<DirectedGraph<Layer*>::Edge> outgoing;
      graph.GetEdgesFrom(layer, outgoing);
      for (uint32_t i = 0; i < outgoing.Length(); i++) {
        DirectedGraph<Layer*>::Edge edge = outgoing.ElementAt(i);
        graph.RemoveEdge(edge);
        if (!graph.NumEdgesTo(edge.mTo)) {
          // If this node also has no edges now, add it to the list
          noIncoming.AppendElement(edge.mTo);
        }
      }
    }

    // If there are no nodes without incoming edges, but there
    // are still edges, then we have a cycle.
    if (noIncoming.IsEmpty() && graph.GetEdgeCount()) {
      // Find the node with the least incoming edges.
      uint32_t minEdges = UINT_MAX;
      Layer* minNode = nullptr;
      for (uint32_t i = 0; i < aLayers.Length(); i++) {
        uint32_t edgeCount = graph.NumEdgesTo(aLayers.ElementAt(i));
        if (edgeCount && edgeCount < minEdges) {
          minEdges = edgeCount;
          minNode = aLayers.ElementAt(i);
          if (minEdges == 1) {
            break;
          }
        }
      }

      if (minNode) {
        // Remove all of them!
        graph.RemoveEdgesTo(minNode);
        noIncoming.AppendElement(minNode);
      }
    }
  } while (!noIncoming.IsEmpty());
  NS_ASSERTION(!graph.GetEdgeCount(), "Cycles detected!");
#ifdef DEBUG
  if (gDumpLayerSortList) {
    fprintf(stderr, " --- Layers after sorting: --- \n");
    DumpLayerList(sortedList);
  }
#endif

  aLayers.Clear();
  aLayers.AppendElements(sortedList);
}