一开始以为整个图是被框住的,冰壶碰到边界会停下来,结果这种越界应该直接continue了的,最终把这个bug改了就AC了
菜鸟写的第一篇文章,这题比较简单,直接贴代码了
#pragma warning(disable:4996) #include<iostream> #include<stdio.h> #include<string.h> #include<queue> #include<vector> #include<string> #include<map> using namespace std; int n, m, x, y, sx, sy, cnt, ex, ey; char a[25][25]; int dirx[] = { 0, 1, 0, -1 }; int diry[] = { 1, 0, -1, 0 }; void dfs(int x, int y, int t){ //if(a[x][y]!='.') return ; //a[x][y]='#'; //cnt++; if (t>10) return;//超过次数,直接返回 for (int k = 0; k<4; k++){ int dx = x; int dy = y; //cout<<"next"<<dx+dirx[k]<<" "<<dy+diry[k]<<endl; //if (dx + dirx[k] == 0 || dx + dirx[k] == n + 1 || dy + diry[k] == 0 || dy + diry[k] == m + 1) continue; if (a[dx + dirx[k]][dy + diry[k]] == '1') continue;//一开始静止的冰壶,如果旁边有个障碍物,是打不破的,没有初速度 //cout<<"start:"<<x<<" "<<y<<endl; while (a[dx][dy] != '1' && a[dx][dy]!='3'){ dx += dirx[k]; dy += diry[k]; } //cout<<"end:"<<dx<<" "<<dy<<endl; if (a[dx][dy] == '3'){//找到了,比较一下返回 cnt = min(cnt, t); return; } if (dx == 0 || dx == n + 1 || dy == 0 || dy == m + 1) { //dfs(dx - dirx[k], dy - diry[k], t + 1); continue;//越界了,跳过,这里卡了好久,哎。。。 } else{ a[dx ][dy ] = '0'; dfs(dx-dirx[k], dy-diry[k], t + 1);//往下一步尝试啦 a[dx][dy ] = '1'; } } } int main(){ //freopen("aaa.txt", "r", stdin); while (scanf("%d%d", &m, &n), m || n){ //cout<<"n="<<n<<"m="<<m<<endl; for (int i = 0; i <= n + 1; i++){ a[i][0] = '1'; a[i][m + 1] = '1'; } for (int i = 0; i <= m + 1; i++){ a[0][i] = '1'; a[n + 1][i] = '1'; } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++){ cin >> a[i][j]; if (a[i][j] == '2'){ sx = i; sy = j; } } //cout<<sx<<" "<<sy<<endl; a[sx][sy] = '0'; cnt = 15; dfs(sx, sy, 1); if (cnt == 15) printf("-1\n"); else printf("%d\n", cnt); } //while (1); return 0; }