JavaScript implementation Puzzle algorithm

Source: Internet
Author: User

The puzzle, is to put 1-8 of these numbers, by moving, in order, for example,

650) this.width=650; "Style=" background-image:none;border-bottom:0px;border-left:0px;margin:0px;padding-left:0px ;p adding-right:0px;border-top:0px;border-right:0px;padding-top:0px; "title=" clipboard "border=" 0 "alt=" clipboard " Src= "http://s3.51cto.com/wyfs02/M02/56/C1/wKiom1SMRSfQ4OaMAAAevMIjEwA357.jpg" height= "/>"

When the arrangement is complete, it becomes

650) this.width=650; "Style=" background-image:none;border-bottom:0px;border-left:0px;padding-left:0px; padding-right:0px;border-top:0px;border-right:0px;padding-top:0px; "title=" clipboard[1] "border=" 0 "alt=" CLIPBOARD[1] "src=" http://s3.51cto.com/wyfs02/M00/56/C1/wKiom1SMRSeh1ENXAAAknmLPh0Q709.jpg "height="/>

The algorithm is implemented as follows:

You can think of the space as 0, each move is the number 0 and the number around the exchange.

1. For example, for the status A, the number 0 in 4 directions to try (some position can not be moved, ignoring the state), get 4 different state a1,a2,a3,a4. Then there can be a tree with a root, a1,a2,a3,a4 are leaf nodes. Detects if the 4 nodes have satisfied the result, and if so, the solution has been found. Then follow this leaf knot, all the way up to its parent node, all the leaf nodes passed, that is, the state of each step. If no, then next.

2. Create a collection that records all the States, and when the new state is not previously there, the state, that is, the leaf node, is placed in a queue.

3. Take a state out of the queue and try it in 4 directions, returning to the first step.

4. Retry until the queue is empty, indicating no solution.

The attachment is code that runs under Chrome.

This article is from "a blog" blog, make sure to keep this source http://cnn237111.blog.51cto.com/2359144/1589636

JavaScript implementation Puzzle algorithm

Related Article

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.