You could model this as a graph and BFS/DFS from index , marking reachable cells. That works but is in the worst case.
Think about what "reachable" means. If you can reach index , you can reach everything from to . You don't need to track individual cells.