贴上代码
判断路径是否走过
static class Stu{
int sheep;
int wolf;
int sheep0;
int wolf0;
public Stu(int sheep, int wolf, int sheep0, int wolf0) {
this.sheep = sheep;
this.wolf = wolf;
this.sheep0 = sheep0;
this.wolf0 = wolf0;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Stu stu = (Stu) o;
return sheep == stu.sheep && wolf == stu.wolf && sheep0 == stu.sheep0 && wolf0 == stu.wolf0;
}
@Override
public int hashCode() {
return Objects.hash(sheep, wolf, sheep0, wolf0);
}
}
完整代码
static class Stu{
int sheep;
int wolf;
int sheep0;
int wolf0;
public Stu(int sheep, int wolf, int sheep0, int wolf0) {
this.sheep = sheep;
this.wolf = wolf;
this.sheep0 = sheep0;
this.wolf0 = wolf0;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Stu stu = (Stu) o;
return sheep == stu.sheep && wolf == stu.wolf && sheep0 == stu.sheep0 && wolf0 == stu.wolf0;
}
@Override
public int hashCode() {
return Objects.hash(sheep, wolf, sheep0, wolf0);
}
}
static int ans = Integer.MAX_VALUE;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sheep = in.nextInt();
int wolf = in.nextInt();
int x = in.nextInt();
transport(new StringBuffer(), sheep, wolf, 0, 0, x, 0, new HashSet<Stu>());
}
private static int transport(StringBuffer sb, int sheep0, int wolf0, int sheep1, int wolf1, int x,
int temp, HashSet<Stu> set) {
if (temp > ans) return 0;
if (sheep0 == 0 && wolf0 == 0) {
if (ans > temp) ans = temp;
System.out.println(sb);
System.out.println("次数:"+temp);
return ans;
}
if (x >= sheep0 + wolf0) {
temp++;
if (ans > temp) ans = temp;
sb.append("运羊:"+sheep0+",运狼:"+wolf0+"\n");
System.out.println(sb);
System.out.println("次数:"+temp);
return ++ans;
}
Stu stu;
for (int i = 0; i <= sheep0 && i <= x; ++i) {
for (int j = 0; j <= wolf0 && i+j <= x; ++j) {
if (i == 0 && j == 0) continue;
stu = new Stu(i, j, sheep0-i, wolf0-j);
if (!set.contains(stu)) {
set.add(stu);
StringBuffer sb1 = new StringBuffer(sb);
if (conditionTrue(sheep0-i, wolf0-j)
&& conditionTrue(sheep1+i, wolf1+j)) {
transport(sb.append("运羊:"+i+",运狼:"+j+"\n"), sheep0-i, wolf0-j, sheep1+i,
wolf1+j, x, temp+1, set);
sb = sb1;
set.remove(stu);
}
}
}
}
return 0;
}
private static boolean conditionTrue(int sheep, int wolf) {
if (sheep > wolf || sheep == 0) {
return true;
}
return false;
}