基本算法之穷举算法

基本算法之穷举算法

穷举算法的思想:从所有的可能的情况搜索正确的答案,其中执行的步骤:

对于一种可能的情况,计算其中的结果。

如果判断的结果的不符合要求就执行第一步来搜索下一个可能的情况

package Main;

import java.util.Scanner;

public class demo2 {

    /**
     * 穷举算法求解鸡兔同笼
     * @param args
     */
    static int chichen,habbit;
    public static void main(String[] args) {
        
        int re,head,foot;
        System.out.println("穷举求解");
        System.out.println("请输入头数:");
        Scanner input = new Scanner(System.in);

        head = input.nextInt();
        foot = input.nextInt();
        re = qiongju(head,foot);
        if(re == 1)
        {
            System.out.println("鸡:"+chichen+"--"+habbit);
        }else{
            System.out.println("无法求解!");
        }
    }

    private static int qiongju(int head, int foot) {
        int re,i,j;
        re=0;
        for(i=0;i<=head;i++)
        {
            j = head-i;
            if(i*2+j*4 == foot)
            {
                re = 1;
                chichen = i;
                habbit = j;
            }
        }
        return re;
    }

}

 

posted on 2014-12-20 22:32  aicpcode  阅读(393)  评论(0编辑  收藏  举报

导航