This article describes the simple implementation of the problem of farmers crossing the river in Java. Share it for your reference, as follows:
1. Problem description
The old man wants to cut fish, dogs, and cats across the river to the other side. There is a boat that can only sit one person. The old man can only bring one animal to cross the river every time. When the old man is away, the dog will bite the cat and the cat will eat fish. How do you cross the river in sequence?
2. Implement code
package demo;import java.util.ArrayList;import java.util.List;public class CrossRiver { List<String> listThis = new ArrayList<String>(); List<String> listThat = new ArrayList<String>(); /*boolean thisFlag = true; boolean thatFlag = false;*/ public CrossRiver() { listThis.add("dog"); listThis.add("fish"); listThis.add("cat"); // listThis.add("people"); } public boolean isSafe(@SuppressWarnings("rawtypes") List list){ if(list.contains("fish")&&list.contains("cat")||list.contains("cat")&&list.contains("dog")){ return false; }else{ return true; } } public void thisTothat(){ String str = listThis.get(0); listThis.remove(str); if(this.isSafe(listThis)){ System.out.println("The farmer takes" + str + "From this shore to the other shore"); System.out.println("This shore" + listThis + "/b" + "Out other shore" + listThat); System.out.println(); listThat.add(str); thatToThis(); }else{ listThis.add(str); thisTothat(); } } public void thatToThis(){ if(listThis.isEmpty()){ System.out.println("This shore" + listThis + "/b" + "Out other shore" + listThat); return; } if(isSafe(listThat)){ System.out.println("The farmer goes from the other shore to this shore"); System.out.println("This shore" + listThis + "/b" + "Outside shore" + listThat); System.out.println(); thisTothat(); }else{ String str = listThat.get(0); listThat.remove(0); if(isSafe(listThat)){ System.out.println("The farmer takes" + str + "From the other shore to this shore"); System.out.println("This shore" + listThis + "/b" + "Outside shore" + listThat); System.out.println(); listThis.add(str); thisTothat(); }else{ listThat.add(str); thatToThis(); } } public static void main(String[] args){ System.out.println("Wulin.com test results:"); System.out.println(); new CrossRiver().thisTothat(); }}Running results:
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.