Grid
来源:互联网 发布:mac系统 文件权限 编辑:程序博客网 时间:2024/05/22 21:46
You are on an nxm 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 of the four cardinal directions. A move cannot go beyond the edges of the grid; it does not wrap. What is the minimum number of moves required to get from the top-left corner to the bottom-right corner?
Input
Each input will consist of a single test case. Note that your program may be run multiple times on different inputs. The first line of input contains two space-separated integers n and m (1≤n,m≤500), indicating the size of the grid. It is guaranteed that at least one of n and m is greater than 1. The next n lines will each consist of m digits, with no spaces, indicating the nxm grid. Each digit is between 0 and 9, inclusive. The top-left corner of the grid will be the square corresponding to the first character in the first line of the test case. The bottom-right corner of the grid will be the square corresponding to the last character in the last line of the test case.
Output
Output a single integer on a line by itself representing the minimum number of moves required to get from the top-left corner of the grid to the bottom-right. If it isn’t possible, output -1.
Example
Input:5 4 2120 1203 3113 1120 1110
Output:
6
题意:每次只能走四方方向之一(上下左右),每次走的步数是当前所在位置上的数值,从左上角到右下角求最短需要几步,不能则输出-1。
求最少步数,用bfs,这里注意开一个二维数组vis[i][j]代表从(0,0)到(i,j)经历了几步
#include<iostream>#include<cstring>#include<queue>using namespace std;const int MAXN = 500 + 7;int vis[MAXN][MAXN];//相当于标记,为0我就可以走,此时到达i,j的步数vis【i】【j】就是到达上一个状态的步数加1char gra[MAXN][MAXN];int n, m, cnt;int d[4][2] = {0, -1, 0, 1,1, 0, -1, 0};struct node{ int x, y, val;}next;bool we(int x, int y){ return x >= 0 && x < n && y >= 0 && y < m;}int bfs(int x, int y, int c){ memset(vis, 0, sizeof(vis)); queue<node> q; node now; now.x=x; now.y=y; now.val=c; q.push(now); while(!q.empty()) { node P = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { next.x= P.x + d[i][0]*P.val; next.y = P.y + d[i][1]*P.val; next.val=gra[next.x][next.y]-'0'; if (we(next.x,next.y) && !vis[next.x][next.y]) { vis[next.x][next.y]= (vis[P.x][P.y] + 1); if(next.x == n-1 && next.y == m-1) { return vis[n-1][m-1]; } q.push(next); } } } return -1;}int main(){ while(cin >> n >> m) { for(int i = 0; i < n; ++i) { cin >> gra[i]; } cout <<bfs(0, 0, gra[0][0]-'0')<< endl; } return 0;}
- grid
- grid
- Grid
- Grid
- grid
- Grid
- grid
- Grid
- ext-grid常见问题 : Grid
- Grid--bigdog
- GRID新手入门
- freedom--grid
- Grid样式
- Grid 概述
- layout-grid
- Grid Computing
- grid 方向键
- EM Grid
- 自己学习中的知识点(2)---jdk8 时间新特性
- zabbix 服务端 zabbix-agent 2.4版本安装
- BigDecimal加减乘除运算
- Mongodb 分片配置
- 计算机语言学习
- Grid
- 安卓打包--优化
- 手机手机信息页面实现
- Android中的Apk的加固(加壳)原理解析和实现
- 求树中两个节点的公共节点
- UE4 Sequence在蓝图中播放和结束
- linux下进程号查看与结束进程
- Tomcat的端口被占用,如何解决?【Mac版】
- 【C++】学习笔记三十三——函数和C风格字符串