Problem
In the ROR game, you play on a team that competes to destroy the opposing team’s base first, making it advantageous to reach the enemy base as quickly as possible. Suppose you’re a team member and are located at position (row: 1, column: 1) on a 5x5 map, while the enemy base is at (row: 5, column: 5). The game map is comprised of cells that can either be passable or blocked by walls. Your character can move up, down, left, or right, and cannot move outside the boundaries of the map.
Given the state of the game map maps, represented as a 2D array where 1s are passable cells and 0s are walls, implement a function solution that returns the minimum number of cells your character must pass through to reach the enemy base located at the bottom-right corner of the map. If it’s impossible to reach the enemy base due to walls blocking the way, return -1.
Constraints
mapsis ann x m2D array, where bothnandmare natural numbers between 1 and 100.nandmcould be the same or different, but the case where bothnandmare 1 will not be provided as input.- The character starts at the top-left corner of the map, and the enemy base is at the bottom-right corner.
- The map only contains 0s and 1s, where 0 indicates a wall and 1 indicates a passable cell.
Example
| maps | answer |
|---|---|
| [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] | 11 |
| [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] | -1 |
Explanation of Examples
- Example 1:
- The character can reach the enemy base by traversing 11 cells, following a path that circumvents walls effectively.
- Example 2:
- Walls block all possible paths to the enemy base, making it impossible to reach, thus the function returns -1.
How to Approach?
Step1: Initialize variables in loop
Code
|
|