added break condition for finding 'end' in bfs/dfs