Castle on the Grid

  • + 0 comments

    JavaScript

    function minimumMoves(grid, startX, startY, goalX, goalY) {
        // Write your code here
        const queue = [[startX, startY, 0]];
        const visited = new Set();
        const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
    
        while (queue.length > 0) {
            const [x, y, moves] = queue.shift();
            const position = `${x}-${y}`;
    
            if (x === goalX && y === goalY) {
                return moves;
            }
    
            visited.add(position);
    
            for (const [dx, dy] of directions) {
                let newX = x + dx;
                let newY = y + dy;
    
                while (
                    newX >= 0 &&
                    newY >= 0 &&
                    newX < grid.length &&
                    newY < grid.length &&
                    grid[newX][newY] !== 'X'
                ) {
                    const newPosition = `${newX}-${newY}`;
    
                    if (!visited.has(newPosition)) {
                        queue.push([newX, newY, moves + 1]);
                        visited.add(newPosition);
                    }
    
                    newX += dx;
                    newY += dy;
                }
            }
        }
    
        return -1; // If a path is not found
    }