題目:見啊哈算法P81頁。 分析:最常見的DFS配合最短路,熟悉寫法。 代碼:
#include<iostream>#include<cstdio>using namespace std ; int n , m , p , q , min_n =999999;int a[51][51] , book[51][51];void dfs(int x,int y,int step){ int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; int tx ,ty ; if(x==p&&y==q){ if(step < min_n){ min_n = step; } return ; } for(int i = 0 ; i <= 3 ; i++){ tx = x + next[i][0]; ty = y + next[i][1]; if(tx<1||tx>n||ty<1||ty>m) continue ;//邊界判斷 if((book[tx][ty]==0)&&(a[tx][ty]==0)){//判斷是否走過或是障礙物 book[tx][ty] = 1 ; dfs(tx,ty,step+1); book[tx][ty] = 0; } } return ;}int main(){ int startx,starty; //讀入n和m,行和列 scanf("%d %d",&n,&m); //讀入迷宮 for(int i = 1 ; i <= n ; i++){ for(int j = 1 ; j <= m ;j++) scanf("%d",&a[i][j]); } //讀入起點和終點 scanf("%d %d %d %d",&startx,&starty,&p,&q); //從起點開始搜索 book[startx][starty] = 1 ; //標記起點在路徑中,防止后面重復走 dfs(startx,starty,0);新聞熱點
疑難解答