给定一个8*8的方格子,A点到B点的最短路径有多少条?
2013-09-20 01:19
232 查看
题目:给定一个8*8的方格子,如下图所示,求A点到B点的最短路径有多少条?用算法实现。(回溯法)
广度优先搜索只能找出一条最短路径
答:从图中可以看出,A点到B点的最短路径为16,即A点横走8小格,纵走8小格才能最快到达B点,这是排列组合的问题,即从最短路径16中选取8个横走的小格子(或者从最短路径16中选取8个纵走的小格子)。所以从A点到B点的最短路径条数,直接可以算出来,即为:
代码如下:
广度优先搜索只能找出一条最短路径
答:从图中可以看出,A点到B点的最短路径为16,即A点横走8小格,纵走8小格才能最快到达B点,这是排列组合的问题,即从最短路径16中选取8个横走的小格子(或者从最短路径16中选取8个纵走的小格子)。所以从A点到B点的最短路径条数,直接可以算出来,即为:
代码如下:
size_t g_num = 0; //统计A点到B点的最短路径条数 void shortestPathNumber(char grid[9][9], int row, int col, int &step) { if (row < 0 || row > 8 || col < 0 || col > 8 || grid[row][col] == '*' || step > 16) { return; } if (row == 0 && col == 8) { if (step == 16) //已到达B点,且等于最短路径16,就累加 { g_num++; } } else { grid[row][col] = '*'; //标记该点已访问 step++; shortestPathNumber(grid, row, col + 1, step); //向4个方向走 shortestPathNumber(grid, row + 1, col, step); shortestPathNumber(grid, row, col - 1, step); shortestPathNumber(grid, row - 1, col, step); grid[row][col] = '.'; //回溯 step--; } } int _tmain(int argc, _TCHAR* argv[]) { char grid[9][9] = {0}; int step = 0; shortestPathNumber(grid, 8, 0, step); //从A点开始搜索 cout<<"A点到B点的最短路径条数为: "<<g_num<<endl; return 0; }
相关文章推荐
- 一个8*8的方格子,A点在左下角,B点在右上角,求A点到B点的最短路径有多少条
- 每天一道LeetCode-----计算从二维数组的左上角到达右下角的所有路径数及最短的那条,如果存在障碍物时又是多少
- [C++]学习从i结点到j结点最短路径共有多少条
- 求格子中的最短路径条数问题
- 求一共有多少种最短路径时
- Project Euler15 给定一个20*20的方格,从左上角到右下角的路径有多少条?(只允许向右和向下走)
- 给定一棵二叉树,找到它的最小深度。最小深度是从根节点到最近叶节点的最短路径上的节点数量
- 给定一棵二叉树,找到它的最小深度。最小深度是从根节点到最近叶节点的最短路径上的节点数量
- 2.算法:棋盘路径问题。走格子/棋盘问题 有多少条路径可走
- 走格子/棋盘问题 有多少条路径可走
- 现在有一个城市销售经理,需要从公司出发,去拜访市内的商家,已知他的位置以及商家的位置,但是由于城市道路交通的原因,他只能在左右中选择一个方向,在上下中选择一个方向,现在问他有多少种方案到达商家地址。给定一个地图map及它的长宽n和m,其中1代表经理位置,2代表商家位置,-1代表不能经过的地区,0代表可以经过的地区,请返回方案数,保证一定存在合法路径。保证矩阵的长宽都小于等于10。
- [C++]学习从i结点到j结点最短路径共有多少条
- 【一道数学题】从(0,0)点经过(x,y)点到达(a,b)点的最短路径有多少条
- Hdu 5314 Happy King(求树上多少个点对(u,v)满足u到v的路径上点权值最大值减最小值不大于给定的K)
- 每天一道LeetCode-----找到有多少条连续路径的和为给定值,路径不需要从根节点出发到达叶子节点
- 模板_Dijkstra最短路径算法
- 二叉树中根到叶子路径中节点和等于给定值的路径
- GCD XOR UVA 12716 找规律 给定一个n,找多少对(a,b)满足1<=b<=a<=n,gcd(a,b)=a^b;
- HDU3790 最短路径问题(双重权值+spfa)
- 最短路径(弗洛伊德算法)