题解 | 棋盘游戏(dfs)

棋盘游戏

https://www.nowcoder.com/practice/368c98c7bff54a30bba29ae1ba017d55

思路

* 确定当前代价计算公式:cost = matrix[i][j] * status

* 确定下一步状态计算公式:new_status = (cost%4)+1;

由于是dfs,非遍历统计类,而是最短路径/最少消耗类,因此需要:(1)更改状态;(2)还原状态。(针对是否访问visit)

传入dfs的状态status及当前总代价cur_cost 可以采用计算公式的形式:如 (cost%4)+1,matrix[i][j] * status。

好处是:未对当前调用栈的遍历进行修改,无需复原状态。

也可以修改变量后调用函数,那么需要复原变量

// dfs(int row, int col, int i_stop, int j_stop, int status, int cost)
visit[row][col] = true;
cost += matrix[row][col] * status;
// cost 由于有取模操作,在dfs中还是传入表达式更方便
for ...
  dfs(row+dir[i][0], col+dir[i][1], (status%4)+1, cost);
cost -= matrix[row][col] * status;
visit[row][col] = false;
#include <iostream>
#include <vector>
#define INF 0x3f3f3f3f
using namespace std;

int matrix[6][6];
vector<vector<bool>> visit(6,vector<bool>(6,false));
// bool visit[6][6];
int res = INF;
int tmp;
int dir[4][2] = {0,1,0,-1,-1,0,1,0};

void dfs(int row, int col, int i_stop, int j_stop, int status, int cur_cost) {
    if(row<0 || row>=6 || col<0 || col>=6) return;
    if(row==i_stop && col==j_stop) {
        res = min(res, cur_cost);
        return;
    }
    if(cur_cost>=res) return;
    if(visit[row][col]==true) return;
    visit[row][col] = true;
    for(int i = 0; i<4; i++) {
        int x = row+dir[i][0];
        int y = col+dir[i][1];
        int cost = matrix[x][y]*status;  // 此步代价
        // status = (cost%4)+1;
        dfs(x, y, i_stop, j_stop, (cost%4)+1, cur_cost+cost);
    }
    visit[row][col] = false;
}

int main() {
    int n = 6;
    for(int i = 0; i<n; i++) {
        for(int j = 0; j<n; j++) {
            cin >> matrix[i][j];
        }
    }
    
    int i_start, j_start, i_stop, j_stop; 
    cin >> i_start >> j_start >> i_stop >> j_stop;
    dfs(i_start, j_start, i_stop, j_stop, 1, 0);
    cout << res << endl;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

11-04 19:05
已编辑
东莞城市学院 单片机
不知道怎么取名字_:你这个要实习两年?哪有这么久的,感觉就是即使你毕业了,但还按实习的话,是不是不用给你缴社保公积金啥的
点赞 评论 收藏
分享
11-15 13:12
已编辑
门头沟学院 Java
斯卡蒂味的鱼汤:知道你不会来数马,就不捞你😂最近数马疯狂扩招,招聘要求挺低的,你能力肯定够,应该就是因为太强了,知道你不会来才不捞你
投递腾讯云智研发等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务