以三色问题为例:
运行结果:
对给定无向图着色,相邻点颜色不能相同,限用3种颜色
在框架基础上的实现:
import
java
.
util
.
Vector
;
public
class
ThreeColor
extends
CombineProblem
{
int
[][]
graph
;
int
start
;
public
ThreeColor
(
int
[][]
graph
,
int
start
)
{
super
();
this
.
graph
=
graph
;
this
.
start
=
start
;
this
.
flag
=
false
;
this
.
n
=
graph
.
length
;
this
.
x
=
new
Integer
[
n
];
}
@Override
public
Vector
<
Comparable
>
makeItem
(
int
k
)
{
Vector
<
Comparable
>
vec
=
new
Vector
<
Comparable
>();
for
(
int
i
=
1
;
i
<=
3
;
i
++)
{
vec
.
add
(
i
);
}
return
vec
;
}
@Override
public
boolean
complete
(
int
k
)
{
return
k
>=
n
;
}
@Override
public
void
printSolution
(
int
k
)
{
for
(
int
i
=
0
;
i
<
x
.
length
;
i
++)
{
System
.
out
.
print
(
x
[
i
]
+
" "
);
}
System
.
out
.
println
();
}
@Override
public
boolean
isPartial
(
int
k
)
{
for
(
int
i
=
0
;
i
<
k
;
i
++)
{
if
(
graph
[
k
][
i
]
==
1
&&
x
[
k
]
==
x
[
i
])
{
return
false
;
}
}
return
true
;
}
}
主函数:
public
class
Main
{
public
static
void
main
(
String
[]
args
)
{
int
[][]
graph
=
{
{
0
,
1
,
1
,
0
},
{
1
,
0
,
0
,
1
},
{
1
,
0
,
0
,
1
},
{
0
,
1
,
1
,
0
}
};
Problem p
=
new
ThreeColor
(
graph
,
0
);
p
.
explore
(
0
);
if
(!
p
.
flag
)
{
System
.
out
.
println
(
"no solution!"
);
}
}
}
1 2 2 1
1 2 2 3
1 2 3 1
1 3 2 1
1 3 3 1
1 3 3 2
2 1 1 2
2 1 1 3
2 1 3 2
2 3 1 2
2 3 3 1
2 3 3 2
3 1 1 2
3 1 1 3
3 1 2 3
3 2 1 3
3 2 2 1
3 2 2 3