Artificial intelligence experiment-eight digital problems

Source: Internet
Author: User

Using state space method to solve eight digital problems (4 UI)

First, the experimental requirements

Eight digital puzzle is also called nine problem, it is in the 3x3 checkered checkerboard, respectively placed table has the number 1, 2, 3, 4, 5, 6, 7, 8 of the eight cards, the initial state of S0, the target state of the SG, as shown in the figure below, requires the use of space to move eight cards from the initial state to reach the target The move rule is: You can only translate a number adjacent to a space (up or down) to a space at a time. The experiment requires the application of breadth-first search strategy to find the solution path from the initial state to the target State, and the programming language is the C-series language.

Arrangement of initial states: 283104765 y= 0+1+1+0+0+4+5+5+5=21 Odd arrangement

Arrangement of the target states: 283104675 y=0+1+1+0+0+4+5+6+5=22 even arrangement

2

8

3

1

4

7

6

5

S0

2

8

3

1

4

6

7

5

sg

Second, data structure

The definition node node is made up of the following members: Array a[3][3] Stores the number of 303 spaces in the current node, 4 node pointers u, D, L, and R, respectively, pointing to the newly formed node in the current node to the upper and lower left and right 4 directions, if it cannot be moved in one direction, the corresponding pointer refers to To NULL, pointer p points to the parent node of the current node, and after the target node is found, a resolution step can be generated up and down the P pointer.

typedef struct NODE

{

int a[3][3];

Node *u;

Node *d;

Node *l;

Node *r;

Node *p;

}

void Search (node * &h)

{

Queue *front, *rear;

Queue *qq,*qtemp,*qfront;

Node *tu,*td,*tl,*tr;

Node *NP;

int temp;

Front=new queue;

};

A node queue is used to compose a queue, which is defined by the following members: the node that the pointer data points to holds the arrangement of the nine graph and 5 pointers, and the pointer next points to the next node in the queue.

typedef struct QUEUE

{

Node *data;

Queue *next;

};

Three, breadth first search

The basic idea of breadth-first search is:

Starting from the initial node H, the node is scaled up and examined to see if it is the target node, or if it is not the target node, it is placed in the queue to be inspected, and the nodes of the N+1 layer are not extended until the nth node is fully expanded and inspected. The nodes in the queue are always arranged in the order of entry, the first entry is in front, and the next entry is in the back row. The search process is as follows:

(1) Initialize node h into the queue, team head pointer front=h;

(2) If front==null, the problem is not solved, exit;

(3) Remove the team head node front, N=front, front point to the bottom of the queue

a node;

(4) Investigate whether the node n is the target node, if so, then ask the solution to obtain,

Exit

(5) To investigate whether the node n is expandable in the upper and lower left and right four directions,

Place its extendable child nodes at the end of the queue and then go to step 2.


The realization of eight digital problems, basically the main framework is LRJ book. Just made a little change and printed the path.

It was the teacher's arrangement, but I found that I had nothing to do with the teacher's arrangement.

#include <cstdio> #include <cstring> #include <vector> #include <set> #include <iostream>

#include <algorithm> #include <queue> using namespace std; const int MAXN = 362880; Up to 9.
case int PATH[MAXN];
typedef int State [9];  State st[maxn],goal;
The state array, where all states are stored in this int dist [MAXN];
const int dx[]={-1,1,0,0};
const int dy[]={0,0,-1,1};
int SS;
For the same node weight///Convert the state to a 9-bit decimal number, and then determine if this step is done based on the unique element nature of the set in the STL set<int>vis;
	void Init () {vis.clear ();} int Try_to_insert (int s) {int v=0;
	for (int i=0;i<9;i++) v=v*10+st[s][i];
	if (Vis.count (v)) return 0;
	Vis.insert (v);
return 1;
	}///output function, recursively record the number of steps to walk down and then output it to void print () {//printf ("21\n");

    int way[100000],temp=0;
        while (PATH[SS]!=SS) {way[temp]=ss;
        temp++;
    SS=PATH[SS];
        } for (int x=temp-1;x>=0;x--) {ss=way[x];
                for (int i=0;i<9;i++) {if (i%3==0) puts ("");
        printf ("%d", st[ss][i]);
        }Puts ("");
    }}///To determine whether there is a solution to the function, according to the relationship between the number of reverse order to solve///two for, and then enumerate a number and the number after it, compare the reverse number bool judge () {int sum1=0;
     int sum2=0;
        for (int i=0;i<9;i++) {if (st[1][i]==0) continue;
            for (int j=i+1;j<9;j++) {if (st[1][j]==0) continue;
        if (St[1][i]>st[1][j]) sum1++;
        }} for (int i=0;i<9;i++) {if (goal[i]==0) continue;
            for (int j=i+1;j<9;j++) {if (goal[j]==0) continue;
        if (Goal[i]>goal[j]) sum2++;
     }} if (sum1%2==sum2%2) return true;
return false;
    }///depth-first search function, using a two-dimensional array to record the state of the walk, by set comparison, and then record int bfs () {init ();
    Path[1]=1;  int front=1,rear = 2;
        Do not use subscript 0, because 0 is treated as not present while (front < rear) {state &s = st [Front];
        if (MEMCMP (goal,s,sizeof (s)) ==0) {///compare return front;
        } int z;  for (z=0;z<9;z++) if (!s[z]) break;
        Find 0 of positions//printf ("%d\n", z);
       int x=z/3,y=z%3; for (int d=0;d<4;d++) {/////into 3x3 squares, then move direction//puts ("F");
            int newx=x+dx[d];
            int newy=y+dy[d]; int newz=newx*3+newy;
            Return 11 lines of sequence, then record//printf ("%d%d\n", x, y);
                if (newx>=0&&newx<3&&newy>=0&&newy<3) {state & T=st[rear];  memcpy (&t,&s,sizeof (s));
                Copy, expand a new node T[newz] = S[z];
                T[Z]=S[NEWZ];
                dist[rear]=dist[front]+1;
                        if (Try_to_insert (rear)) {///If insert is successful, modify the tail pointer path[rear]=front;
                rear++;  }}} front++; Change the first pointer of the team after the extension is completed} return 0; Failed} int main () {for (int i=0;i<9;i++) scanf ("%d", &st[1][i]);///Start status for (int i=0;i<9;i++) scan F ("%d", &goal[i]);
    Target State if (judge ()) {int ans = BFS ();
    Ss=ans;
    Print (); if (ans>0) printF ("%d\n", Dist[ans]);
    } else printf ("No solution \ n");
return 0;

 }


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.