刚开始看到最短路,第一反应是bfs,但是题中说明可以破坏路障,所以需要保存状态,bfs保存状态很困难,所以改用dfs,
1.第一次没注意破坏的障碍应该回溯,所以wa
2.第二次用dfs的时候保存当前状态的时候用了全局变量,所以一直没调出来。
#include <iostream>
#include <cstdio>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <stack>
#include <stdlib.h>
#include <stdio.h>
#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define uint unsigned int
#define l(x) x<<1
#define r(x) x<<1|1
#define ms(a,b) memset(a,b,sizeof(a))
using namespace std;
struct node {
int x, y;
node(){}
node(int a,int b):x(a),y(b){}
bool operator==(const node&b) {
return (x == b.x&&y == b.y);
}
};
int h, w, mmap[33][33],res;
node beg, en;
int dir[4][2] = {0,-1,0,1,1,0,-1,0};
int run(const node &f, node &r, int d) {
r = f;
r.x += dir[d][0];
r.y += dir[d][1];
if (mmap[r.x][r.y] == 1) return 0;
while (1) {
if (r.x >= h || r.x < 0 ||
r.y >= w || r.y < 0) return 0;
if (mmap[r.x][r.y] == 3) {
return 2;
}
if (mmap[r.x][r.y] == 1) {
r.x -= dir[d][0];
r.y -= dir[d][1];
return 1;
}
r.x += dir[d][0];
r.y += dir[d][1];
}
}
void dfs(node no, int times) {
if (times == 10)
return;
node temp;
for (int i = 0; i < 4; i++) {
if (run(no, temp, i) == 1) {
mmap[temp.x + dir[i][0]][temp.y + dir[i][1]] = 0;
dfs(temp, times + 1);
mmap[temp.x + dir[i][0]][temp.y + dir[i][1]] = 1;
}
else if (run(no, temp, i) == 2) {
res = min(res, times+1);
}
}
}
int main() {
while (scanf("%d%d", &w, &h), h) {
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
scanf("%d", &mmap[i][j]);
if (mmap[i][j] == 2) {
beg.x = i;
beg.y = j;
//uesd[i][j] = 1;
}
else if (mmap[i][j] == 3) {
en.x = i;
en.y = j;
}
}
}
res = INF;
dfs(beg,0);
if (res == INF)
printf("-1\n");
else
printf("%d\n", res);
}
return 0;
}