-
Notifications
You must be signed in to change notification settings - Fork 0
/
RoadsAndCities-YasinShabaniVaraki.cpp
127 lines (103 loc) · 2.76 KB
/
RoadsAndCities-YasinShabaniVaraki.cpp
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <vector>
#include <stack>
#include <random>
#include <ctime>
using namespace std;
void dfs(int city, vector<vector<int>>& graph, vector<bool>& visited, stack<int>& order) {
visited[city] = true;
for (int neighbor : graph[city]) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited, order);
}
}
order.push(city);
}
vector<int> findCityOrder(int n, vector<vector<int>>& matrix) {
vector<vector<int>> graph(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 1 && matrix[j][i] == 0) {
graph[i].push_back(j);
}
}
}
vector<bool> visited(n, false);
stack<int> order;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i, graph, visited, order);
}
}
vector<int> cityOrder;
while (!order.empty()) {
cityOrder.push_back(order.top() + 1);
order.pop();
}
return cityOrder;
}
vector<vector<int>> generateMatrixTestCase(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int> dis(0, 1);
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int val = dis(gen);
matrix[i][j] = val;
matrix[j][i] = 1 - val;
}
}
return matrix;
}
void printMatrix(const vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
int main() {
int n;
cout << "Enter the size of the matrix: ";
cin >> n;
char choice;
cout << "Do you want to generate a random matrix? (y/n): ";
cin >> choice;
vector<vector<int>> matrix;
if (choice == 'y' || choice == 'Y') {
matrix = generateMatrixTestCase(n);
cout << "Generated matrix:" << endl;
printMatrix(matrix);
}
else {
cout << "Enter the matrix values (0 or 1):" << endl;
matrix.resize(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
}
vector<int> order = findCityOrder(n, matrix);
if (order.size() == n) {
cout << "The order of cities is:" << endl;
for (int city : order) {
cout << city << endl;
}
}
else {
cout << "There is no valid path of length " << n << "." << endl;
}
cout << "Do you want to end the program? (y/n): ";
cin >> choice;
if (choice == 'y' || choice == 'Y') {
return 0;
}
else {
matrix.clear();
main();
}
}