1 2
.#...
.#.#.
...#.
15
3 3 4 5 ..# .#. #..
IMPOSSIBLE
题目大意:
刚开始是在小镇里面,小镇到荒地要a元,荒地到小镇要b元。问,怎么走才能花费的最少
思路:
基础的广搜。。。不过我要吐槽。。。为啥我第一种方法是wa了,害我重新又写了好一会儿TAT
#include
#include
#include
#include
using namespace std;
typedef long long ll;
typedef pair P;
const int maxn = 500 + 5;
int n, m;
int a, b;
char atlas[maxn][maxn];
int step[maxn][maxn];
int dx[4] = {1, 0, 0, -1};
int dy[4] = {0, 1, -1, 0};
int val[maxn][maxn];
void init(){
memset(step, 0, sizeof(step));
memset(atlas, 0, sizeof(atlas));
memset(val, -1, sizeof(val));
memset(step, -1, sizeof(step));
scanf("%d%d", &a, &b);
for (int i = 0; i < m; i++){
scanf("%s", atlas[i]);
}
val[0][0] = a;
queue que;
que.push(make_pair(0, 0));
while (!que.empty()){
P tmp = que.front();
que.pop();
for (int i = 0; i <= 3; i++){
int x = tmp.first + dx[i];
int y = tmp.second + dy[i];
if (x < 0 || y < 0 || x >= m || y >= n) continue;
if (atlas[x][y] == '#' || atlas[x][y] == '\0') continue;
if (val[x][y] != -1) continue;
if (val[tmp.first][tmp.second] == a){
val[x][y] = b;
}
else val[x][y] = a;
que.push(make_pair(x, y));
}
}
/*
printf("check\n");
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
printf("%d ", val[i][j]);
}
printf("\n");
}
*/
}
ll bfs(){
queue
que;
que.push(make_pair(0, 0));
step[0][0] = 0;
while (!que.empty()){
P tmp = que.front();
que.pop();
for (int i = 0; i < 4; i++){
int x = tmp.first + dx[i];
int y = tmp.second + dy[i];
if (x < 0 || y < 0 || x >= m || y >= n) continue;
if (atlas[x][y] == '#' || atlas[x][y] == '\0') continue;
if (step[x][y] != -1) continue;
step[x][y] = step[tmp.first][tmp.second] + val[x][y];
//printf("step[%d][%d] = %d\n", x, y, step[x][y]);
que.push(make_pair(x, y));
}
}
if (step[m-1][n-1] == -1) printf("IMPOSSIBLE\n");
else printf("%d\n", step[m-1][n-1]);
}
int main(){
while (scanf("%d%d", &n, &m) == 2){
init();
bfs();
}
return 0;
}