2021-07-19 虾皮前端笔试第三题 搬货员的最小转向次数

这篇博客讲述了作者在处理一个编程挑战时遇到的困难,主要涉及JavaScript代码的编写和调试。作者抱怨了在有限的代码编辑器视图下操作的不便,以及对C++的偏好。博客展示了代码实现,包括二维数组的初始化、DFS算法和路径查找。文章以一个实际的输入示例结束,演示了如何处理S字符并找到最短路径。

当时急了,没做出来,这个笔记本写代码是真的恶心,加上虾皮的那个界面,能看到的代码就那么七八行。

导致我急了,结束后又缝缝补补,把代码写出来了,但是也不知道对不对。

要是给我拿c++我早写出来了,气死我了。

let line; 
let inputline = 1;
let m, n;
let mp;
let snum = 0;
while(line = gets(inputline)) {
    if (!line) break;
    if (inputline === 1) {
        m = line.split(" ")[1];
        n = line.split(" ")[0];
        m = Number(m);
        n = Number(n);
        mp = new Array();
        for (let i=0; i<m; i++) {
            mp[i] = new Array(n);
        }
    }
    else if (inputline !== 1) {
        for (let i=0; i<line.length; i++) {
            mp[inputline - 2][i] = line[i];
            if (line[i] === 'S') snum += 1;
        }
    }
    inputline += 1;
}

let dx = [-1, 0, 1, 0];
let dy = [0, 1, 0, -1];
let dre = 1; 
// 0 1 2 3
// t r b l

let flag = new Array();
for (let i=0; i<m; i++) {
    flag[i] = new Array();
    for (let j=0; j<n; j++) {
        flag[i][j] = new Array(false, false, false, false);
    }
}

let maxtimes = 999999999;

function main () {
    // r = 1
    flag[0][0][1] = true;
    dfs(0, 0, 1, 0);
    console.log(maxtimes);
}


function dfs(x, y, d, times) {
    console.log(x, y, d, times);
    let goods = [];
    for (let i=0; i<4; i++) {
        let gx = x + dx[i];
        let gy = y + dy[i];
        if (gx < 0 || gy <0 || gx >= m || gy >= n) break;
        if (mp[gx][gy] === 'S') {
            goods.push([gx, gy]);
            mp[gx][gy] = 'X';
            snum -= 1;
        }
    }

    if (snum === 0) {
        if (times < maxtimes) {
            maxtimes = times;
        }
    }
    
    for (let i=0; i<4; i++) {
        let nd = i;
        let nx = x + dx[d];
        let ny = y + dy[d];
        let nt = times;
        if (nx < 0 || ny <0 || nx >= m || ny >= n) continue;
        if (flag[nx][ny][nd] === true) continue;
        if (mp[nx][ny] === 'X') continue;
        flag[nx][ny][nd] = true;
        if (d !== nd) nt += 1;
        dfs(nx, ny, nd, nt);
    }
    for (let good of goods) {
        mp[good[0]][good[1]] = 'S';
    }
    snum += goods.length;
}

main()

function gets (x) {
    if (x === 1) {
        return "4 3";
    }
    if (x === 2) {
        return "..x.";
    }
    if (x ===3) {
        return "....";
    }
    if (x === 4) {
        return "x..S";
    }
    if (x >4) return null;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值