-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.cpp
More file actions
94 lines (78 loc) · 2.71 KB
/
Copy pathgraph.cpp
File metadata and controls
94 lines (78 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "graph.h"
using namespace std;
/*--------------------------------------------------
Parse XML content and build graph
--------------------------------------------------*/
Graph buildGraphFromXML(const string& xmlContent)
{
Graph graph;
XMLDocument doc;
if (doc.Parse(xmlContent.c_str()) != XML_SUCCESS)
{
cerr << "Error: Invalid XML\n";
return graph;
}
XMLElement* users = doc.FirstChildElement("users");
if (!users) return graph;
for (XMLElement* user = users->FirstChildElement("user");
user;
user = user->NextSiblingElement("user"))
{
XMLElement* idElem = user->FirstChildElement("id");
if (!idElem || !idElem->GetText()) continue;
int userId = stoi(idElem->GetText());
graph[userId]; // ensure node exists
XMLElement* followers = user->FirstChildElement("followers");
if (!followers) continue;
for (XMLElement* follower = followers->FirstChildElement("follower");
follower;
follower = follower->NextSiblingElement("follower"))
{
XMLElement* fid = follower->FirstChildElement("id");
if (!fid || !fid->GetText()) continue;
int followerId = stoi(fid->GetText());
graph[userId].push_back(followerId);
}
}
return graph;
}
/*--------------------------------------------------
Export graph to DOT file
--------------------------------------------------*/
void exportToDot(const Graph& graph, const string& dotFile)
{
ofstream out(dotFile);
out << "digraph SocialNetwork {\n";
out << " node [shape=circle, style=filled, fillcolor=lightblue];\n";
for (const auto& [user, followers] : graph)
{
for (int f : followers)
{
out << " " << user << " -> " << f << ";\n";
}
}
out << "}\n";
out.close();
}
/*--------------------------------------------------
Render DOT using bundled Graphviz
--------------------------------------------------*/
void renderGraph(const string& dotFile, const string& outputImage)
{
// Use system-installed Graphviz (assumes dot is in PATH)
string command = "dot -Tjpg " + dotFile + " -o " + outputImage;
int ret = system(command.c_str());
if (ret != 0) {
cerr << "Error: Graphviz failed with exit code " << ret << endl;
}
}
/*--------------------------------------------------
Public API (matches assignment)
--------------------------------------------------*/
void drawXMLGraph(const string& xmlContent, const string& outputImage)
{
const string dotFile = "temp_graph.dot";
Graph graph = buildGraphFromXML(xmlContent);
exportToDot(graph, dotFile);
renderGraph(dotFile, outputImage);
}