sicily 1135 飞越原野 bfs
这题因为两个地方打错变量,WA了好几次。
#include <iostream> #include <queue> #include <memory.h> #define MAX 101 using namespace std; struct status { int x, y; int step; int remain_fly_step; }; int dir_x[] = {0, 1, -1, 0}; int dir_y[] = {1, 0, 0, -1}; char my_map[MAX][MAX]; bool isvisit[MAX][MAX][MAX]; int d; int m,n; void bfs(); status fly(status, int , int ); int main() { while (cin >> m >> n >> d) { for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) cin >> my_map[i][j]; memset(isvisit, false, sizeof(isvisit)); bfs() } return 0; } void bfs() { queue<status> Q; status tmp,p; p.x = 0; p.y = 0; p.remain_fly_step = d; p.step = 0; Q.push(p); isvisit[p.x][p.y][p.remain_fly_step] = true; while (!Q.empty()) { p = Q.front(); Q.pop(); if (p.x == m-1 && p.y == n-1) { cout << p.step << endl; return ; } for (int i = 0; i < 4; i++) { tmp.x = p.x + dir_x[i]; tmp.y = p.y + dir_y[i]; tmp.remain_fly_step = p.remain_fly_step; tmp.step = p.step + 1; if (tmp.x >= 0 && tmp.x < m && tmp.y >= 0 && tmp.y < n && !isvisit[tmp.x][tmp.y][tmp.remain_fly_step] && my_map[tmp.x][tmp.y] == 'P') { isvisit[tmp.x][tmp.y][tmp.remain_fly_step] = true; Q.push(tmp); } } for (int i = 0; i < 4; i++) { for (int j = 1; j <= p.remain_fly_step; j++) { tmp = fly(p, i, j); if (tmp.x >= 0 && tmp.x < m && tmp.y >= 0 && tmp.y < n && !isvisit[tmp.x][tmp.y][tmp.remain_fly_step] && my_map[tmp.x][tmp.y] == 'P' && tmp.remain_fly_step >= 0) { Q.push(tmp); isvisit[tmp.x][tmp.y][tmp.remain_fly_step] = true; } } } } cout << "impossible" << endl; } status fly(status p, int mode, int step) { status tmp; switch (mode) { case 0: tmp.x = p.x; tmp.y = p.y + step; tmp.step = p.step + 1; tmp.remain_fly_step = p.remain_fly_step - step; break; case 1: tmp.x = p.x; tmp.y = p.y - step; tmp.step = p.step + 1; tmp.remain_fly_step = p.remain_fly_step - step; break; case 2: tmp.x = p.x + step; tmp.y = p.y; tmp.step = p.step + 1; tmp.remain_fly_step = p.remain_fly_step - step; break; case 3: tmp.x = p.x - step; tmp.y = p.y; tmp.step = p.step + 1; tmp.remain_fly_step = p.remain_fly_step - step; break; } return tmp; }