思路

* 确定当前代价计算公式: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")