Categories
JavaScript Телерик

Решение на задача – Labyrinth Escape

Решение на задача: Labyrinth Escape

Изпит: JavaScript основи

Точки в BGCoder: 100 от 100

function Solve(params) {
    var input = params[0].split(" ");
    var rowsCount = parseInt(input[0]);
    var columnsCount = parseInt(input[1]);

    var labyrinthNumbers = new Array(rowsCount);
    var visitedCells = new Array(rowsCount);

    var number = 1;
    for (var i = 0; i < rowsCount; i++) {
        labyrinthNumbers[i] = new Array(columnsCount);
        visitedCells[i] = new Array(columnsCount);
        for (var j = 0; j < columnsCount; j++) {
            labyrinthNumbers[i][j] = number;
            visitedCells[i][j] = 0;
            number++;
        }
    }
    input = params[1].split(" ");
    var rowPosition = parseInt(input[0]);
    var columnPosition = parseInt(input[1]);
    visitedCells[rowPosition][columnPosition] = 1;
    var numbersSum = 0;
    numbersSum += labyrinthNumbers[rowPosition][columnPosition];
    var directions = new Array(rowsCount);
    for (var i = 0; i < rowsCount; i++) {
        directions[i] = new Array(columnsCount);
        for (var j = 0; j < columnsCount; j++) {
            directions[i][j] = params[i + 2][j];
        }
    }
    var steps = 1;
    while (true) {
        switch (directions[rowPosition][columnPosition]) {
            case "l":
                columnPosition -= 1;
                break;
            case "r":
                columnPosition += 1;
                break;
            case "u":
                rowPosition -= 1;
                break;
            case "d":
                rowPosition += 1;
                break;
        }
        if (rowPosition < 0 || rowPosition >= rowsCount || columnPosition < 0 || columnPosition >= columnsCount) {
            return 'out ' + numbersSum;
        }

        if (visitedCells[rowPosition][columnPosition] === 1) {
            return 'lost ' + steps;
        }

        visitedCells[rowPosition][columnPosition] = 1;
        numbersSum += labyrinthNumbers[rowPosition][columnPosition];
        steps++;
    }
}