2464: 中山市选[2009]小明的游戏
Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 963 Solved: 394
[ Submit][ Status][ Discuss]
Description
小明最近喜欢玩一个游戏。给定一个n * m的棋盘,上面有两种格子#和@。游戏的规则很简单:给定一个起始位置和一个目标位置,小明每一步能向上,下,左,右四个方向移动一格。如果移动到同一类型的格子,则费用是0,否则费用是1。请编程计算从起始位置移动到目标位置的最小花费。
Input
输入文件有多组数据。
输入第一行包含两个整数n,m,分别表示棋盘的行数和列数。
输入接下来的n行,每一行有m个格子(使用#或者@表示)。
输入接下来一行有四个整数x1, y1, x2, y2,分别为起始位置和目标位置。
当输入n,m均为0时,表示输入结束。
Output
对于每组数据,输出从起始位置到目标位置的最小花费。每一组数据独占一行。
Sample Input
2 2
@#
#@
0 0 1 1
2 2
@@
@#
0 1 1 0
0 0
Sample Output
2
0
居然还有没发现的水题,BFS就行了
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
char str[505][505];
typedef struct
{
int x;
int y;
}Point;
Point now, temp;
int dp[505][505];
queue<Point> q;
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
int main(void)
{
int n, m, i, x2, y2, val;
while(scanf("%d%d", &n, &m), n!=0 || m!=0)
{
for(i=1;i<=n;i++)
scanf("%s", str[i]+1);
scanf("%d%d%d%d", &now.x, &now.y, &x2, &y2);
now.x++, now.y++, x2++, y2++;
memset(dp, 62, sizeof(dp));
dp[now.x][now.y] = 0;
q.push(now);
while(q.empty()==0)
{
now = q.front();
q.pop();
for(i=0;i<=3;i++)
{
temp.x = now.x+dir[i][0];
temp.y = now.y+dir[i][1];
if(temp.x<1 || temp.x>n || temp.y<1 || temp.y>m)
continue;
val = 0;
if(str[temp.x][temp.y]!=str[now.x][now.y])
val = 1;
if(dp[now.x][now.y]+val<dp[temp.x][temp.y])
{
dp[temp.x][temp.y] = dp[now.x][now.y]+val;
q.push(temp);
}
}
}
printf("%d\n", dp[x2][y2]);
}
return 0;
}