UVa539

题目:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=480

UVa539,求无向图的最长路径

采用逐个点深搜的方式,找到一条路径,维护最大值

#include<stdio.h>
#include<string.h>
#define MAX 26
int map[MAX][MAX],visited[MAX][MAX];
int longest,vector,edge;
void dfs(int i,int d){
	int k;
	if(d>longest)
		longest=d;
	for(k=0;k<MAX;k++){
		if(!visited[k][i]&&!visited[i][k]&&map[i][k]&&k!=i){
			visited[i][k]=visited[k][i]=1;
			dfs(k,d+1);
			visited[i][k]=visited[k][i]=0;           //回溯时要改回来,是防止后面的遍历干扰前面的
		}
	}
}
int main()
{
	int i,node1,node2;
	while(scanf("%d%d",&vector,&edge)!=EOF&&(vector||edge)){
		memset(map,0,sizeof(map));
		for(i=0;i<edge;i++){
			scanf("%d%d",&node1,&node2);
			map[node1][node2]=1;
			map[node2][node1]=1;
		}
		longest=0;
		for(i=0;i<vector;i++){
			memset(visited,0,sizeof(visited));
			dfs(i,0);                                             //找最长路径,逐个节点深搜
		}
		printf("%d\n",longest);
	}
	return 0;
}


你可能感兴趣的:(vector)