2015-2016 ACM-ICPC Grid

13 篇文章 0 订阅

题目地址:http://codeforces.com/gym/100819/attachments

题目:

You are on the top left square of an m × n grid, where each square on the grid has a digit on it.From a given square that has digit k on it, a move consists of jumping exactly k squares in one ofthe four cardinal directions. What is the minimum number of moves required to get from the topleft corner to the bottom right corner?

Input

The first line of input contains two space-separated positive integers m and n (1 ≤ m, n ≤ 500). Itis guaranteed that at least one of m and n is greater than 1. The next m lines each consists of ndigits, describing the m × n grid. Each digit is between 0 and 9.

Output

Print, on a single line, a single integer denoting the minimum number of moves needed to get fromthe top-left corner to the bottom-right corner. If it is impossible to reach the bottom-right corner,print IMPOSSIBLE instead.

思路:

bfs。走的路是格子里的数值。

代码:

#include<iostream>
#include<queue>
using namespace std;
char maze[505][505];
int d[505][505];
int m,n;
const int INF=10000000;
typedef pair<int,int> P;
int k;
void bfs(int x,int y)
{
	queue<P> q;
    q.push(P(0,0));
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            d[i][j]=INF;
        }
    }
    d[0][0]=0;
    while(q.size())
    {
        P p=q.front();q.pop();
        if(p.first==m-1&&p.second==n-1){k=1;break;}
        int dx[4] = { 0,0,-(maze[p.first][p.second] - 48),(maze[p.first][p.second] - 48) };
	    int dy[4] = { -(maze[p.first][p.second] - 48),(maze[p.first][p.second] - 48),0,0 };
        for(int i=0;i<4;i++)
        {
            int nx=p.first+dx[i],ny=p.second+dy[i];
            if(nx>=0&&nx<m&&ny>=0&&ny<n&&d[nx][ny]==INF)
            {
                q.push(P(nx,ny));
                d[nx][ny]=d[p.first][p.second]+1;
            }
        }
    }
	if(k==1)cout<<d[m-1][n-1]<<endl;
	else cout<<"IMPOSSIBLE"<<endl;
}
int main()
{
    cin>>m>>n;
    k=0;
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            cin>>maze[i][j];
        }
    }
    bfs(0,0);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值