图论算法 欧拉图

n 代表点数   m 代表边数

第一种深度搜索,自己写的。最后判断边数都走完等

第二种思路也差不多,但是巧妙的运用到度数参数,最后只要判断这个就行。。类似于2个回路拼起来

package com.bluecup.org;

import java.util.Scanner;

//所有边都走过,且仅一次,所有点都走过,且是回路
public class EulerGraph {
	static boolean used[] = new boolean[20];
	static boolean map[][] = new boolean[20][20];
	static int f[][] = new int[20][20];
	static int n, m;
	static int num;
	static int start;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		n = scan.nextInt();
		m = scan.nextInt();
		for (int i = 0; i < m; i++) {
			int start, stop;
			start = scan.nextInt();
			stop = scan.nextInt();
			f[start][stop] = 1;
		}
		start = 1;
		if (dp(1, 1))
			System.out.println("yes");
		else
			System.out.println("no");
	}

	private static boolean dp(int x, int y) {
		// TODO Auto-generated method stub
		int i;
		if (x != y) {
			if (map[x][y] == false) {
				map[x][y] = true;
			} else
				return false;
			num++;
		}
		used[y] = true;
		if (num == m)// 边都走完
		{
			for (i = 1; i <= n + 1; i++)// 判断是否所有点都走完
			{
				if (used[i] == false)
					break;
			}
			if (i == n + 1)// 判断回路
			{
				if (y == start)
					return true;
			}
		}
		for (i = 1; i <= n; i++) {
			if (f[y][i] == 1)
				if (dp(y, i))
					return true;
		}
		num--;
		map[x][y] = false;
		used[y] = false;
		return false;
	}

}


 

 

 

package com.bluecup.org;

import java.util.Scanner;

public class EulerGraph1 {

	static boolean used[] = new boolean[20];
	static boolean map[][] = new boolean[20][20];
	static int f[][] = new int[100][2];
	static int n, m;
	static int num;
	static int start;
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scan = new Scanner(System.in);
		n = scan.nextInt();
		m = scan.nextInt();
		for (int i = 0; i < m; i++) {
			int start, stop;
			start = scan.nextInt();
			stop = scan.nextInt();
			map[start][stop] = true;
			f[start][0]++;//出度
			f[stop][1]++;//入度
		}
		used[1]=true;
		dp(1);
		int i=1;
		for(;i<=n;i++)
			if(used[i]);
			else break;
		if(i==n+1)
		{
			for(i=1;i<=n;i++)
			{
				if(f[i][0]==f[i][1])
					;
				else break;
			}
		}
		if(i>n)
			System.out.println("yes");
		else
			System.out.println("no");
	}
	private static void dp(int x) {
		// TODO Auto-generated method stub
		for(int i=1;i<=n;i++)
		{
			if(x!=i&&map[x][i]&&!used[i])
			{
				used[i]=true;
				dp(i);
			}
		}
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值