当前位置: 代码迷 >> 综合 >> hdu - 1010 - Tempter of the Bone
  详细解决方案

hdu - 1010 - Tempter of the Bone

热度:98   发布时间:2024-01-10 13:36:05.0

题意:一个N*M的地图,走过的点不能再走,X为墙不可走,能否从点S到点D恰好用时T。(1 < N, M < 7; 0 < T < 50)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1010

——>>有点邯郸学步的感觉,寒假时用cin输入数据,轻松AC,后来慢慢改成了用scanf来输入,今天,这道坑爹的题目交了n次也是WA,代替了n种方式后发现,是输入的问题,猜想是输入的地图有空格……

超时优化的思想:

1、可走格子数少于T时,一定不ok;

2、从格子A到格子B,无论怎么走,步数的奇偶性相同。

用时很少的写法:

#include <cstdio>
#include <cmath>
#include <iostream>using namespace std;char MAP[8][8];
int N, M, T, s_x, s_y, d_x, d_y;
int dx[] = {-1, 0, 1,  0};
int dy[] = { 0, 1, 0, -1};bool ok;void dfs(int x, int y, int cur)
{if(ok) return;int temp = T - cur - abs(d_x-x) - abs(d_y-y);if((temp < 0) || (temp % 2 == 1)) return;for(int i = 0; i < 4; i++){int new_x = x + dx[i];int new_y = y + dy[i];if(new_x >= 0 && new_x < N && new_y >= 0 && new_y < M && MAP[new_x][new_y] != 'X'){if(new_x == d_x && new_y == d_y && cur+1 == T) ok = 1;else{MAP[new_x][new_y] = 'X';dfs(new_x, new_y, cur+1);MAP[new_x][new_y] = '.';}}}
}
int main()
{int i, j, sum;while(scanf("%d%d%d", &N, &M, &T) == 3){if(N == 0 && M == 0 && T == 0) return 0;sum = 1;for(i = 0; i < N; i++){//getchar();for(j = 0; j < M; j++){//MAP[i][j] = getchar();//scanf("%c", &MAP[i][j]);cin>>MAP[i][j];if(MAP[i][j] == 'S'){s_x = i;s_y = j;}else if(MAP[i][j] == 'D'){d_x = i;d_y = j;}else if(MAP[i][j] == 'X') sum++;}}sum = N*M - sum;ok = 0;MAP[s_x][s_y] = 'X';if(T <= sum)dfs(s_x, s_y, 0);if(ok) printf("YES\n");else printf("NO\n");}return 0;
}

vis[][]数组写法:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>using namespace std;const int maxn = 7 + 10;
int dx[] = {-1, 1,  0, 0};
int dy[] = { 0, 0, -1, 1};
char MAP[maxn][maxn];
bool ok, vis[maxn][maxn];
int N, M, T, Dx, Dy;void dfs(int x, int y, int cur)
{if(ok) return;if(cur == T){if(x == Dx && y == Dy){ok = 1;return;}elsereturn;}int temp = T - cur - (Dx - x) - (Dy - y);if(temp < 0 || (temp&1)) return;for(int i = 0; i < 4; i++){int newx = x + dx[i];int newy = y + dy[i];if(newx >= 0 && newx < N && newy >= 0 && newy < M && MAP[newx][newy] != 'X' && !vis[newx][newy]){vis[newx][newy] = 1;dfs(newx, newy, cur+1);vis[newx][newy] = 0;}}
}int main()
{int Sx, Sy, i, j;while(scanf("%d%d%d", &N, &M, &T) == 3){if(!N && !M && !T) return 0;for(i = 0; i < N; i++){for(j = 0; j < M; j++){cin>>MAP[i][j];if(MAP[i][j] == 'S'){Sx = i;Sy = j;}else if(MAP[i][j] == 'D'){Dx = i;Dy = j;}}}ok = 0;memset(vis, 0, sizeof(vis));vis[Sx][Sy] = 1;dfs(Sx, Sy, 0);if(ok)printf("YES\n");elseprintf("NO\n");}return 0;
}