# Getting WA even if my answer is correct

Question: - CSES-Labyrinth

My code

``````
#include <bits/stdc++.h>
using namespace std;

string ans;
vector<int> grapheck;

void dfs(int **visited, int **graph, int x, int y, int bm, int bn, int m, int n)
{
visited[x][y] = 1;
if(graph[x][y] == 3)
{
grapheck.push_back(1);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++) visited[i][j] = 1;
}

return;
}
if(visited[x+1][y] == 0 && graph[x+1][y] != 0){
dfs(visited, graph, x+1, y, bm, bn, m, n);
ans.push_back('D');
}
if(visited[x-1][y] == 0 && graph[x-1][y] != 0){
dfs(visited, graph, x-1, y, bm, bn, m, n);
ans.push_back('U');
}
if(visited[x][y+1] == 0 && graph[x][y+1] != 0){
dfs(visited, graph, x, y+1, bm, bn, m, n);
ans.push_back('R');
}
if(visited[x][y-1] == 0 && graph[x][y-1] != 0){
dfs(visited, graph, x, y-1, bm, bn, m, n);
ans.push_back('L');
}
}
int main()
{
int m, n;
cin >> m >> n;

int am = 0, an = 0;
int bm, bn;

int **graph;
int **visited;

char ch;

visited = new int*[m+2];
graph = new int*[m+2];
for(int i = 0; i < m+2; i++)
{
visited[i] = new int[n+2];
graph[i] = new int[n+2];
}

for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
cin >> ch;
visited[i][j] = 0;
if(ch == '#') graph[i][j] = 0;
else if(ch == '.') graph[i][j] = 1;
else if(ch == 'A')
{
graph[i][j] = 2;
am = i;
an = j;
}
else if(ch == 'B')
{
graph[i][j] = 3;
bm = i;
bn = j;
}

}
}

// for(int i = 1; i <= m; i++)
// {
//     for(int j = 1; j <= n; j++) cout << graph[i][j];
//     cout << endl;
// }

for(int i = 0; i < n+2; i++)
{
visited[i] = 1;
graph[i] = 'x';
visited[m+1][i] = 1;
graph[m+1][i] = 'x';
}

for(int i = 0; i < m+2; i++)
{
visited[i] = 1;
graph[i] = 'x';
visited[i][n+1] = 1;
graph[i][n+1] = 'x';
}

dfs(visited, graph, am, an, bm, bn, m+2, n+2);

if(grapheck.size() == 1)
{
cout << "YES" << endl;
int i = ans.size();
cout << i << endl;
i--;

for( ; i >= 0; i--)
{
cout << ans[i];
}
cout << endl;
}
else cout << "NO" << endl;

return 0;
}

``````

Half of the test cases is giving AC but the other half is giving WA.

For example in Test 4, I am getting WA, but my solution is correct.

The grid in question is So, Defintely, ‘R’ is correct answer. But ‘DRU’ is also correct path, then why it is wrong as in the question I have to print any valid path.

read the output instructions, it specifies shortest path.

If there is a path, print the length of the shortest such path and its description as a string consisting of characters `L` (left), `R` (right), `U` (up), and `D` (down). You can print any valid solution.

1 Like