GRID MOVES - Editorial

Author, Tester and Editorialist : Jitin

SIMPLE

QUICK EXPLANATION:

Use a 2D array to keep track of the cells which you have visited. If you an unvisited cell increment the count of laddus eaten. Take care of boundary conditions and respawning.

SOLUTIONS:

C++ implementation
``````	#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")

using namespace std;

typedef long long ll;
typedef long double ld;
#define fast_cin()                    \
ios_base::sync_with_stdio(false); \
cin.tie(NULL);                    \
cout.tie(NULL)

const int mod = 1e9 + 7;
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
bool isValid(int posX, int posY, int n)
{
return posX > 0 && posX <= n - 1 && posY > 0 && posY <= n - 1;
}
void solve()
{
int n;
cin >> n;
int x, y;
cin >> x >> y;
string s;
cin >> s;
int curr_x = x, curr_y = y;
int ate[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
ate[i][j] = 0;
}
}
ate[curr_x][curr_y] = 1;

for (int i = 0; i < s.length(); i++)
{
if (s[i] == 'L' && isValid(curr_x, curr_y - 1, n))
{
curr_y--;
}
else if (s[i] == 'R' && isValid(curr_x, curr_y + 1, n))
{
curr_y++;
}
else if (s[i] == 'U' && isValid(curr_x - 1, curr_y, n))
{
curr_x--;
}
else if (s[i] == 'D' && isValid(curr_x + 1, curr_y, n))
{
curr_x++;
}
else
{
curr_x = x;
curr_y = y;
}
if (ate[curr_x][curr_y] != 1)
{
ate[curr_x][curr_y] = 1;
}
}
}

signed main()
{
fast_cin();
solve();
return 0;
}
``````
Python implementation
``````  for _ in range(int(input())):
n = int(input())
pos_x,pos_y = map(int,input().split())
commands = input()

result = 1
curr_x,curr_y = pos_x,pos_y

def isvalidGrid(x,y,n) -> bool:
return x>=0 and x<=n-1 and y>=0 and y<=n-1

ate = {(curr_x,curr_y):1}

for i in commands:
if i=='L' and isvalidGrid(curr_x,curr_y-1,n):
curr_x,curr_y = curr_x,curr_y-1
elif i=='R' and isvalidGrid(curr_x,curr_y+1,n):
curr_x,curr_y = curr_x,curr_y+1
elif i=='U' and isvalidGrid(curr_x-1,curr_y,n):
curr_x,curr_y = curr_x-1,curr_y
elif i=='D' and isvalidGrid(curr_x+1,curr_y,n):
curr_x,curr_y = curr_x+1,curr_y
else:
curr_x,curr_y = pos_x,pos_y
if not ate.get((curr_x,curr_y)):
ate[(curr_x,curr_y)]=1
result += 1

print(result)
``````