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);
}
}
}
}
1552

被折叠的 条评论
为什么被折叠?



