This is the link to the problem here We have to tell the order in which the letters(like bricks) have to be laid in order for the wall to be stable. ie; for example if the input is
ZOAAMM
ZOAOMM
ZOOOOM
ZZZZOM
Then if I lay 'A's first then they will fall to the ground since in order to lay the letter 'A' I need to lay the letters 'Z' and 'O' first. If I lay all O's first then they will also fall on the ground since some of the O's depend on the 'Z' below to be laid first.
The answer for the above is 'ZOMA' or 'ZOAM' both are valid answers. If it's not possible then we should print -1. What I did in my code is that I first made a graph. For the example above, the graph will be O-> A since A depends on O. O->M since M also depends on O. Z->O since O depends on Z.
Then if there is a cycle in the graph then that means it is not possible to lay the wall so I print -1 If there is no cycle then the answer exists, and to get the answer I do a topological sort.
All the example test cases passed, but when I submit, I get a wrong answer. I don't know which test case could be failing. Can you let me know any case which my code is failing for please.
#include<bits/stdc++.h>
using namespace std;
vector<int>adj[26]; // adjacency list to store the graph
int n,m; // n rows each with a string of size m
string s[30];
bool vis[26]; //for topological sort
int visited[26];//for cycle detection
stack <char> mystack;
bool flag = 0;
void cycledfs(int node) // returns -1 if cycle detected
{
if(visited[node] == -1)
{
flag = 1;
return;
}
visited[node] = -1;
for(int i = 0; i < adj[node].size(); i++)
{
if(visited[adj[node][i]] != 1)
{
cycledfs(adj[node][i]);
}
}
visited[node] = 1;
}
void dfs(int node) // if cycle is not detected we do the topological sorting
{
if(!vis[node])
{
vis[node] = 1;
for(int i = 0; i < adj[node].size(); i++)
{
if(!vis[adj[node][i]])
dfs(adj[node][i]);
}
mystack.push(node+'A');
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
while(t--)
{
cin>>n>>m;
set <char> t; // set to store all the unique letters which are my vertices of the graph
for(int i = 0; i <n; i++)
{
cin>>s[i];
for(int j = 0; s[i][j]!='\0';j++)
t.insert(s[i][j]);
if(i)
{
for(int j = 0; s[i][j]!='\0';j++)
{
auto it = find(adj[s[i][j]-'A'].begin(), adj[s[i][j]-'A'].end(), (s[i-1][j]-'A'));
if(((s[i][j]-'A') != (s[i-1][j]-'A')) &&(it==adj[s[i][j]-'A'].end()))
adj[s[i][j]-'A'].push_back((s[i-1][j]-'A'));
}
}
}
//initializing stuff
flag = 0;
memset(visited, 0, sizeof(visited));
memset(vis, 0, sizeof(vis));
for(char i: t)//CYCLE CHECKING
{
//cout<<(i-'A')<<"\n";
if(visited[i-'A'] == 0)
cycledfs(i-'A');
if(flag)
break;
}
if(flag)
cout<<"-1\n";
else //doing topological sort if no cycle
{
string result ="";
for(char x: t)
dfs(x-'A');
while(!mystack.empty())
{
char ans = mystack.top();
result.push_back(ans);
mystack.pop();
}
cout<<result<<"\n";
for(int i = 0; i < 26; i++) //clearing
adj[i].clear();
}
}
}
Aucun commentaire:
Enregistrer un commentaire