PHP Example code to implement the Chess Vault program:
Problem Description:
Suppose the chess board has 5*5 a total of 25 squares. Design a program so that the pieces from the initial position (the Checkerboard Number 1 position) to start the vault, the board can go through the grid, each lattice only allowed to walk once. Requirements:
1) output a solution (using a two-dimensional array to record the process of horse jumping, that is [step number, checkerboard number], the upper left corner is the beginning of the first step), 2) to find out the total number of solutions
The checkerboard number is:
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21st |
22 |
23 |
24 |
25 |
Analysis: Simple DFS ...
#include <stdio.h> #include <string.h> int path[26],path1[26],res ; int vis[26][26];int dx[8]={-2,-1,1,2,2,1,-1,-2},dy[8]={-1,-2,2,-1,1,2,2,1};void DFS (int x,int y,int num,int step) {if (x<1 | | x>5 | | y<1 | | y>5 | | vis[x][y])//cross-border or visited return; if (step==25) {res++; Path1[step]=num; for (int i=1;i<=25;i++) path[i]=path1[i]; Return } if (!vis[x][y]) {vis[x][y]=1; for (int i=0;i<8;i++) {path1[step]=num; DFS (X+dx[i],y+dy[i], (x+dx[i]-1) *5+y+dy[i],step+1); } vis[x][y]=0; }}int Main () {memset (vis,0,sizeof (VIS));//Can be omitted here, because the system is assigned a value of 0 DFS (1,1,1,1) when defining global variables; printf ("Total number of solutions:%d, one of the solutions: \ n", res); for (int i=1;i<=25;i++) printf ("[%d,%d]\n", I,path[i]); return 0; }