题目描述
有一个 m×m 的棋盘,棋盘上每一个格子可能是红色、黄色或没有任何颜色的。你现在要从棋盘的最左上角走到棋盘的最右下角。
任何一个时刻,你所站在的位置必须是有颜色的(不能是无色的), 你只能向上、下、左、右四个方向前进。当你从一个格子走向另一个格子时,如果两个格子的颜色相同,那你不需要花费金币;如果不同,则你需要花费 1 个金币。
另外, 你可以花费 2 个金币施展魔法让下一个无色格子暂时变为你指定的颜色。但这个魔法不能连续使用, 而且这个魔法的持续时间很短,也就是说,如果你使用了这个魔法,走到了这个暂时有颜色的格子上,你就不能继续使用魔法; 只有当你离开这个位置,走到一个本来就有颜色的格子上的时候,你才能继续使用这个魔法,而当你离开了这个位置(施展魔法使得变为有颜色的格子)时,这个格子恢复为无色。
现在你要从棋盘的最左上角,走到棋盘的最右下角,求花费的最少金币是多少?
输入格式
第一行包含两个正整数 m,n,以一个空格分开,分别代表棋盘的大小,棋盘上有颜色的格子的数量。
接下来的 n 行,每行三个正整数 x,y,c, 分别表示坐标为 (x,y) 的格子有颜色 c。
其中 c=1 代表黄色,c=0 代表红色。 相邻两个数之间用一个空格隔开。 棋盘左上角的坐标为 (1,1),右下角的坐标为 (m,m)。
棋盘上其余的格子都是无色。保证棋盘的左上角,也就是 (1,1) 一定是有颜色的。
输出格式
一个整数,表示花费的金币的最小值,如果无法到达,输出 -1
。
既然要求最小,那必然是广搜(其实深搜也可以)
根据题目要求模拟爆搜,然后一步步剪枝
DEBUG了半天,终于从70到ac了。。。
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> board;
vector<vector<int>> cost;
int m,n;
int sx[5] = {0,0,-1,1};// 上下左右四个方向
int sy[5] = {-1,1,0,0};
void bfs(){
queue<pair<int,int>> que;
queue<int> color;
queue<int> last;
queue<bool> usmig;
queue<int> now;
que.push(make_pair(0,0));
color.push(board[0][0]);
usmig.push(false);
last.push(1);
now.push(0);
while(!que.empty()){
int x0 = que.front().first;
int y0 = que.front().second;
int c = color.front();bool mig = usmig.front();int la = last.front();int us = now.front();
que.pop();color.pop();usmig.pop();now.pop();
for(int i = 0; i<4;i++){
int a = x0 + sx[i];
int b = y0 + sy[i];
if(a>=m || a<0 || b >=m || b<0 || (sx[la] + a == 0 && sy[la] + b == 0)){
continue;
}
if(c != board[a][b] || c == 2){//不同色
if(board[a][b] == 2){//无色
if(mig == true)//无色没魔法不能前进
continue;
if(us + 2 < cost[a][b]){ //经济上可行,用魔法到
cost[a][b] = us + 2;
now.push(us+2);
que.push(make_pair(a,b));
color.push(board[x0][y0]);
last.push(i);
usmig.push(true);
}
}else{//有颜色
if(us + 1 < cost[a][b]){ //经济上可行,花钱到
cost[a][b] = us + 1;
now.push(us+1);
que.push(make_pair(a,b));
color.push(board[a][b]);
last.push(i);
usmig.push(false);//魔法必然恢复
}
}
}else{ //同色
if(us < cost[a][b]){
cost[a][b] = us;
que.push(make_pair(a,b));
now.push(us);
color.push(board[a][b]);
last.push(i);
usmig.push(false);//走到同色魔法一定能恢复
}else{
continue;//同色又不划算的话没有保留的必要
}
}
}
}
}
int main(){
cin >> m >> n;
board.resize(n,vector<int>(n,2));
cost.resize(n,vector<int>(n,INT_MAX));
for(int i = 0; i<n;i++){
int x,y,c;
cin >> x >> y >> c;
board[--x][--y] = c;
}
cost[0][0] = 0;
bfs();
if(cost[m-1][m-1] == INT_MAX)
cout << -1;
else
cout << cost[m-1][m-1] <<endl;
/* DUBUG
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
if (cost[i][j] == INT_MAX) {
cout << "I "; // 未访问的格子输出 I
} else {
cout << cost[i][j] << " ";
}
}
cout << endl;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}*/
}