PHP Backtracking algorithm sample sharing

Source: Internet
Author: User
This paper mainly introduces the implementation of PHP backtracking algorithm, combined with specific examples of the implementation of the PHP backtracking algorithm and the use of methods, involving strings and arrays of recursion, traversal, operation and other related operations skills, the need for friends can refer to, hope to help everyone.

Problem:

A bull camel 2 bags of rice, a cow camel a bag of rice, two calf camel a bag of rice, ask 100 bags of rice How many head Daniel, how many heads of cattle, how many calves?

Implementation code:


<?php/* * k = 2x + y + 1/2z value range * 0 <= x <= 1/2k * 0 <= y <= k * 0 <= Z < = 2k * x, y, z max 2k */$daMi $result = Array (), function isOk ($t, $daMi, $result) {/*{{{*/$total = 0; $hash = array (); $hash [1] = 2; $hash [2] = 1; $hash [3] = 0.5; for ($i =1; $i <= $t; $i + +) {$total + = $result [$i] * $hash [$i];} if ($total <= $daMi) {return true;} return false;} /*}}}*/function Backtrack ($t, $daMi, $result) {/*{{{*///Recursive exit if ($t > 3) {//Output optimal solution if ($daMi = = (2 * $result [1] + $result [2  ] + 0.5 * $result [3]) {  echo "optimal solution, Rice: ${dami}, Daniel: $result [1], Medium bull: $result [2], calf: $result [3]\n";} return;} for ($i = 0; $i <= 2 * $daMi, $i + +) {$result [$t] = $i,//Pruning if (IsOk ($t, $daMi, $result)) {  backtrack ($t +1, $daMi, $result);} $result [ $T] = 0; }}/*}}}*/backtrack (1, $daMi, $result);? >

Running results such as:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.