又是一道DFS的简单题,不过貌似用DP会更好,但是没有写。
#include<stdio.h>
#include
<string.h>
#include
<math.h>
#define max 25
typedef 
struct point_type
int x;
  
int y;
}
point;
point p[max];
int n,m,visited[max],dis[max][max],min_lenth,times;

int cal_dis(point a,point b)

  
return abs(a.x-b.x)+abs(a.y-b.y);
}


void DFS(int pos,int sum_lenth,int count)
int i;
  
if(count==times){
     
if(sum_lenth+dis[pos][0]<min_lenth)
       min_lenth
=sum_lenth+dis[pos][0];
   
return;
   }

  
for(i=0;i<=times;i++){
    
if(visited[i]==1||sum_lenth+dis[pos][i]>min_lenth) 
      
continue;
    visited[i]
=1;
    DFS(i,sum_lenth
+dis[pos][i],count+1); //这而我写成了count++,WA了N次
    visited[i]=0;  //这步是回溯的关键
   }

}
  
  
int main()
int t,i,j;
  scanf(
"%d",&t);
  
while(t--){
    min_lenth
=10000;
    memset(visited,
0,sizeof(visited));
    scanf(
"%d%d%d%d%d",&n,&m,&p[0].x,&p[0].y,&times);
     
for(i=1;i<=times;i++){
       scanf(
"%d%d",&p[i].x,&p[i].y);
       visited[i]
=0;
      }

    
for(i=0;i<=times;i++)
        
for(j=0;j<=times;j++){
        dis[i][j]
=cal_dis(p[i],p[j]);
        
//printf("%d ",dis[i][j]);
        }

    visited[
0]=1;
    DFS(
0,0,0);
    printf(
"The shortest path has length %d\n",min_lenth);
  }

 
return 0;
}

再做几道DFS就去学校了,开始做BFS,总之先把搜索搞熟练了再说其他的。