农夫过河问题,从JAVA代码看算法
这个是解决简单的农夫问题的代码代码如下:publicclassAcrossTheRiver{//定义三个String对象publicstaticfinalStringsh...
这个是解决简单的农夫问题的代码
代码如下:
public class AcrossTheRiver {
// 定义三个String对象
public static final String sheepName = "羊";
public static final String wolfName = "狼";
public static final String cabbageName = "白菜";
// 判断两个货物之间关系是否友好 ..
public static boolean isFriendly(Goods goods1, Goods goods2){
if (goods1 != null){
if (goods1.getGoodsName().trim().equals(sheepName)){
if (goods2 == null){
return true;
}
else{
return false;
}
}
else if (goods1.getGoodsName().trim().equals(wolfName)){
if (goods2 == null || goods2.getGoodsName().trim().equals(cabbageName)){
return true;
}
else{
return false;
}
}
else if(goods1.getGoodsName().trim().equals(cabbageName)){
if (goods2 == null || goods2.getGoodsName().trim().equals(wolfName)){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
else{
return false;
}
}
// 我就直接写在主方法里了
public static void main(String [] args){
boolean isSuccess = false;
LinkedList<Goods> beforeCrossing = new LinkedList<Goods>();
LinkedList<Goods> afterCrossing = new LinkedList<Goods>();
beforeCrossing.add(new Goods(sheepName));
beforeCrossing.add(new Goods(cabbageName));
beforeCrossing.add(new Goods(wolfName)); 展开
代码如下:
public class AcrossTheRiver {
// 定义三个String对象
public static final String sheepName = "羊";
public static final String wolfName = "狼";
public static final String cabbageName = "白菜";
// 判断两个货物之间关系是否友好 ..
public static boolean isFriendly(Goods goods1, Goods goods2){
if (goods1 != null){
if (goods1.getGoodsName().trim().equals(sheepName)){
if (goods2 == null){
return true;
}
else{
return false;
}
}
else if (goods1.getGoodsName().trim().equals(wolfName)){
if (goods2 == null || goods2.getGoodsName().trim().equals(cabbageName)){
return true;
}
else{
return false;
}
}
else if(goods1.getGoodsName().trim().equals(cabbageName)){
if (goods2 == null || goods2.getGoodsName().trim().equals(wolfName)){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
else{
return false;
}
}
// 我就直接写在主方法里了
public static void main(String [] args){
boolean isSuccess = false;
LinkedList<Goods> beforeCrossing = new LinkedList<Goods>();
LinkedList<Goods> afterCrossing = new LinkedList<Goods>();
beforeCrossing.add(new Goods(sheepName));
beforeCrossing.add(new Goods(cabbageName));
beforeCrossing.add(new Goods(wolfName)); 展开
展开全部
好繁琐...一堆if else...你不觉得很麻烦吗? 我给你提个思路. 你每个Goods object里面都设置一个天敌的list.
Goods g = new Goods("Sheep");
g.setEnemy(Arrays.asList(new String[]{"wolf" }));
Goods g2 = new Goods("Cabbage");
g2.setEnemy(Arrays.asList(new String[]{"Sheep" }));
Goods g3 = new Goods("Wolf");
g3.setEnemy(Arrays.asList(new String[]{}));
这样你的在check isFriendly的时候, 只要检测2个物品的enemyList里面没有自己就可以了.
return !good1.getEnemyList().contains(good2.getName()) && !good2.getEnemyList().contains(good1.getName());
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询