Hi I tried to solve this problem based on bfs https://mirror.codeforces.com/problemset/problem/198/B . Also I have implemented it well and it passes for 28 test cases butgives MEMORY LIMIT EXCEE. on test 29 . May be there is something to learn here . please anybody hep if you can figure out whats wrong . Here is my submission https://mirror.codeforces.com/contest/198/submission/85799856 . THANKS