이 기사는 자바에서 강을 건너는 농민의 문제의 간단한 구현에 대해 설명합니다. 다음과 같이 참조에 대해 공유하십시오.
1. 문제 설명
노인은 강을 건너 다른쪽으로 물고기, 개, 고양이를 자르고 싶어합니다. 한 사람 만 앉을 수있는 보트가 있습니다. 노인은 매번 강을 건너만 한 마리의 동물을 데려 올 수 있습니다. 노인이 떠날 때 개는 고양이를 물고 고양이는 물고기를 먹을 것입니다. 당신은 어떻게 강을 순서대로 건너는가?
2. 코드 구현
패키지 데모; import java.util.arraylist; import java.util.list; public class crossriver {list <string> listthis = new arraylist <string> (); List <string> list that = new ArrayList <string> (); /*부울 thisflag = true; 부울 thatflag = false;*/ public crossriver () {listthis.add ( "dog"); listthis.add ( "물고기"); listthis.add ( "cat"); // listthis.add ( "people"); } public boolean issafe (@suppresswarnings ( "rawtypes") 목록) {if (list.contains ( "fish") && list.contains ( "cat") || list.contains ( "cat") && list.contains ( "dog")) {return false; } else {return true; }} public void theTothat () {String str = listthis.get (0); listthis.remove (str); if (this.issafe (listthis)) {System.out.println ( "농부는" + str + "를이 해안에서 다른 해안으로 가져갑니다"); System.out.println ( "이 쇼어" + 목록 + "/b" + "Out Out Out Out Out" + ListTatt that); System.out.println (); list that.add (str); thattothis (); } else {listthis.add (str); thistothat (); }} public void thattothis () {if (listthis.isempty ()) {system.out.println ( "이 쇼어" + 목록 + "/b" + "다른 해안" + 목록); 반품; } if (issafe (listThat)) {system.out.println ( "농부는 다른 해안 에서이 해안으로갑니다"); System.out.println ( "이 쇼어" + 목록 + "/b" + "해외 해외" + 목록); System.out.println (); thistothat (); } else {string str = list that.get (0); 목록 .remove (0); if (issafe (listthat)) {system.out.println ( "농부는" + str + "를 다른 해안 에서이 해안으로 가져갑니다"); System.out.println ( "이 쇼어" + 목록 + "/b" + "해외 해외" + 목록); System.out.println (); listthis.add (str); thistothat (); } else {list that.add (str); thattothis (); }} public static void main (String [] args) {System.out.println ( "wulin.com 테스트 결과 :"); System.out.println (); New Crossriver (). thistothat (); }}실행 결과 :
Java 알고리즘에 대한 자세한 내용은이 사이트에 관심이있는 독자들이 주제를 볼 수 있습니다. "Java 데이터 구조 및 알고리즘 자습서", "Java Operation Dom Node Tips 요약", "Java 파일 및 디렉토리 작동 팁 요약"및 "Java Cache Operation Tips의 요약"을 볼 수 있습니다.
이 기사가 모든 사람의 Java 프로그래밍에 도움이되기를 바랍니다.