简介
刷题经常会使用bfs 和 dfs
总结
问题, 从0,0 走到 n,m 最小花费是多少?
0, 花费2元
1, 花费1元
2, 此路不通
code dfs
void dfs(vector<vector<int> >& v, int x, int y, int money) {
if(x == n - 1 && y == m - 1) {
minMoney = min(minMoney,money);
return ;
}
for(int i=0; i<4; i++){
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if(nx < 0 || nx >= n || ny < 0 || ny >= m || v[nx][ny] == 2){
continue;
}
int oldv = v[nx][ny];
int t = v[nx][ny] == 0 ? 2 : 1;
v[nx][ny] = 2;
dfs(v,nx,ny,money + t);
v[nx][ny] = oldv;
}
return ;
}
int bfs(vector<vector<int> >& v, int x, int y) {
queue<int> q;
q.push(x * N + y);
vector<vector<int>> dis(n,vector<int>(m,INF));// dis[i][j] (0,0) -> (i,j) 的最小开销
dis[0][0] = 0;
while(!q.empty()) {
int t = q.front(); q.pop();
int cx = t / N;
int cy = t % N;
for(int i = 0;i < 4;i ++) {
int nx = cx + dir[i][0];
int ny = cy + dir[i][1];
if(nx < 0 || ny < 0 || nx == n || ny == m || v[nx][ny] == 2) continue;
int cost = v[nx][ny] == 0 ? 2 : 1;// 到 (nx,ny) 的开销
if(dis[nx][ny] > dis[cx][cy] + cost) {
// 更新
dis[nx][ny] = dis[cx][cy] + cost;
q.push(nx * N + ny);
}
}
}
return dis[n - 1][m - 1];
}
};