Algorithm Note _183: Previous questions nine reflow (Java)

Source: Internet
Author: User

Directory

1 Problem Description

2 Solutions

 1 problem description Problem Descriptionas in the nine of the first figure below, there is a 1~8 digital card, and a grid is empty. The cards in the lattice adjacent to the empty lattice can be moved to a space. After several moves, the situation shown in the second diagram can be formed.

we recorded the first picture as: 12345678.
Note the situation of the second picture as: 123.46758
It is clear that the numbers are recorded in order from top to bottom, left to right, and spaces are marked as periods.
The task of this topic is to know the initial state and final state of the nine, and to find the minimum number of steps that can be reached. If no number of steps are reached, output-1. Input FormatThe first line contains the initial state of the nine, and the second line contains the final state of the nine. output Formatoutputs a minimum number of steps, or 1 if no scheme exists. Sample Input12345678.
123.46758Sample Output3Sample Input13524678.
46758123.Sample Output A

2 Solutions

The following code refers to the reference from the end of the article, the core use BFS solution, which requires the minimum number of moves in the BFS Traversal, the first time to reach the match is the minimum number of moves, this is not good proof, but you can think carefully, it should be so.

This version of The C + + Edition is The version of theJava version .

The specific code is as follows:

Importjava.util.ArrayList;ImportJava.util.HashSet;ImportJava.util.Scanner; Public classMain { Public StaticString start, end;  Public Static intx1, y1;//start with empty grid coordinates in the space state start     Public Static int[] move = {{ -1,0},{1,0},{0,-1},{0,1}};//Move one step up, down, left, right, respectively     Public StaticHashset<string> set =NewHashset<string> ();//used to store the result of each move of an empty lattice for weighing        Static classMove {//inner class, the result of storing the empty lattice after moving one step         Public intX//empty lattice Position horizontal axis         Public intY//empty lattice ordinate move step number         Public intStep//Record Final         PublicString temp;//current nine Gongge states                 PublicMove (intXintYintstep, String temp) {             This. x =x;  This. y =y;  This. Step =step;  This. temp =temp; }    }         Public voidBFs () { for(inti = 0;i < Start.length (); i++) {//finding the position of the empty lattice in the initial state of nine Gongge            if(Start.charat (i) = = '. ') {x1= I/3; Y1= i% 3; }} ArrayList<Move> list =NewArraylist<move>(); List.add (NewMove (x1, y1, 0, start));        Set.add (start);  while(!List.isEmpty ()) {Move now= List.get (0); List.remove (0); if(Now.temp.equals (end)) {//exits directly when the current status is the final stateSystem.out.println (Now.step); return; }             for(inti = 0;i < 4;i++) {//four types of walking options                intx = now.x + move[i][0]; inty = now.y + move[i][1]; if(X < 0 | | x > 2 | | y < 0 | | y > 2)//Nine appears out of bounds                    Continue; intStep = now.step + 1; Charn = now.temp.charAt (x * 3 + y);//gets the new position character for the current walkString temp0 =now.temp; Temp0= Temp0.replace (n, '-');//exchange '. ' Characters and N charactersTemp0 = Temp0.replace ('. '), N); Temp0= Temp0.replace ('-', '. ')); if(!set.contains (TEMP0)) {//determine if the current walking result has been walkedSet.add (TEMP0); List.add (NewMove (x, y, step, temp0)); }}} System.out.println ("-1"); return; }         Public Static voidMain (string[] args) {main test=NewMain (); Scanner in=NewScanner (system.in); Start= In.next ();//the initial state of the nine GonggeEnd = In.next ();//the final state of the nine GonggeTest.bfs (); }}

Resources:

1. Blue Bridge Cup nine re-platoon (wide search)

Algorithm Note _183: Previous questions nine reflow (Java)

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.