find() method in set takes O(n) time . So, it will give tle.

You need to create visited array as we do in simple bfs but since negative indices are present,we need to create to create map, but operations on map are usually slow, so it will

also give tle.

Now,what you can do??

You have to create visited array in such a way that negative indices get handled.So we need to shift the negative part to postitve somehow.

Maximum negative it can go is:- 5 x1000 x 20 = 1000000= 1000005(we always increase the size a little )

So this extra must be added in the visited array and hence the indices will never go negative.

Size of visited array = Maximum positive side + this extra = 5x1000x20 + 1000000= 2000000 = 2000001.

Rest part is simple bfs.