九度OJ(1091)棋盘游戏

来源:互联网 发布:手机上的数据处理软件 编辑:程序博客网 时间:2024/04/30 22:47
题目1091:棋盘游戏           

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:622

解决:155

题目描述:

    有一个6*6的棋盘,每个棋盘上都有一个数值,现在又一个起始位置和终止位置,请找出一个从起始位置到终止位置代价最小的路径:
1、只能沿上下左右四个方向移动
2、总代价是没走一步的代价之和
3、每步(从a,b到c,d)的代价是c,d上的值与其在a,b上的状态的乘积
4、初始状态为1

每走一步,状态按如下公式变化:(走这步的代价%4)+1。

输入:

    第一行有一个正整数n,表示有n组数据。
    每组数据一开始为6*6的矩阵,矩阵的值为大于等于1小于等于10的值,然后四个整数表示起始坐标和终止坐标。

输出:

    输出最小代价。

样例输入:
11 1 1 1 1 11 1 1 1 1 11 1 1 1 1 11 1 1 1 1 11 1 1 1 1 11 1 1 1 1 10 0 5 5
样例输出:
23
这个题目本身并不难,主要是因为这是在九度上面A的第一个四星题目,所以拿出来share一下,很简单,DFS和BFS都能做,我用DFS一遍过了,下面是代码:
#include <iostream>#include <vector>#include <queue>#include <functional>#include <cstdlib>using namespace std;int sx,sy,ex,ey,ans;//起始点,终点坐标;queue<int>q;int dir[][2]={{-1,0},{1,0},{0,1},{0,-1}};int visit[6][6];int map[6][6];void DFS(int x,int y,int sum,int statu){    if(sum<ans)    {        if(x==ex&&y==ey)        {            ans=sum;            return ;        }        for(int i=0;i<4;i++)        {            int nextx=x+dir[i][0];            int nexty=y+dir[i][1];            if(visit[nextx][nexty]&&nextx>=0&&nextx<6&&nexty>=0&&nexty<6)            {                int cost=statu*map[nextx][nexty];                visit[nextx][nexty]=0;                DFS(nextx,nexty,sum+cost,cost%4+1);                visit[nextx][nexty]=1;            }        }    }}int main(){    int k;    cin>>k;    while(k--)    {        for(int i=0;i<6;i++)        {            for(int j=0;j<6;j++)            {                cin>>map[i][j];                visit[i][j]=1;            }        }        cin>>sx>>sy>>ex>>ey;        ans=1000000;        DFS(sx,sy,0,1);        cout<<ans<<endl;    }    return 0;}