题目:给定一个8*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; }