-
Notifications
You must be signed in to change notification settings - Fork 0
/
Circle_of_Strings.cpp
84 lines (66 loc) · 1.76 KB
/
Circle_of_Strings.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
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
void dfs(int node, vector<int> adj[], vector<bool> &visited)
{
visited[node] = true;
for(auto it : adj[node])
{
if(!visited[it])
dfs(it, adj, visited);
}
}
int isCircle(vector<string> &arr) {
vector<int> adj[26];
vector<int> Indegree(26, 0);
vector<int> Outdegree(26, 0);
for(int i = 0; i < arr.size(); i++)
{
string temp = arr[i];
int u = temp[0] - 'a';
int v = temp[temp.size()-1] - 'a';
adj[u].push_back(v);
adj[v].push_back(u);
Indegree[u]++;
Outdegree[v]++;
}
for(int i = 0; i < 26; i++)
{
if(Indegree[i] != Outdegree[i])
return 0;
}
int node = arr[0][0] - 'a';
vector<bool> visited(26, false);
dfs(node, adj, visited);
for(int i = 0; i < 26; i++)
{
if(Outdegree[i] && !visited[i])
return 0;
}
return 1;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N;
cin >> N;
vector<string> A;
string s;
for (int i = 0; i < N; i++) {
cin >> s;
A.push_back(s);
}
Solution ob;
cout << ob.isCircle(A) << endl;
}
return 0;
}
// } Driver Code Ends