javascript

2D Array Path - C3 AI - CRM - Full Stack - 11/11/21

/*
You are given an NxN map where each cell consists of a non-negative integer value 
representing the height of the cell.
 
There is a player on the map that stands at the top-left cell. 
The player wants to get to the bottom-right cell. 
The player can only move up, down, left, or right. 
Also, the player can move between two cells if the absolute difference in height between them is less or equal to the player jump power.
 
Given a map and a player jump power, 
write a function that returns true if the player can reach the bottom right cell, 
or false otherwise.
 
0 1 1 3 4
3 4 2 0 1
2 2 2 4 3
1 3 4 3 1
1 2 1 1 0
 
jump Power = 3
0 1 1
    2
    2
    4
    1 1 0
    
jump power = 1
0 1 2
    2
2 2 2
1
1 2 1 1 0
 
*/

function hasPath(map, jumpPower) {
  let queue = [{
    x: 0,
    y: 0
  }]
  
  let visited = {};
               
  while (!queue.empty) {
    let position = queue.pop
    
    if (visited[(position.x, position.y]) {
      continue; 
    } else {
      if (position.y == map.length && position.x == map[0].length) {
      // reached the bottom right 
      return true;
    } else {
      let right = map[position.y][position.x + 1]
      
      let left = map[position.y][position.x - 1]
      
      if (position.y + 1 < map.length) {
        let bottom = map[position.y + 1][position.x]
        if (jumpPower + map[position.x][position.y] >= bottom) {
          queue.push({
            x: postion.x,
            y: position.y + 1
          });
        }
      }
      
      let top = map[position.y - 1][position.x]
      
      visited[(position.x, position.y)] = true
    }
    
    //if (map[positon.x][position.y])
  }
  
  return false; 
}
Was this helpful?