This is a problem involving the calculation of the number of steps;
For this problem, my usual practice is to add a variable to the DFS function, step;
In this way, we can easily control and record ( the smallest ) steps when we carry out the deep search function recursion.
Topic:
-
This has a maze, with 0~8 rows and 0~8 columns:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,1
0 represents the road, and 1 represents the wall.
Now enter the coordinates of a road as the starting point, and then enter a road as the coordinates as the end point, ask at least a few steps to reach the end from the starting point?
(Note: One step is to move from one sitting punctuation to the next to the left and right adjacent coordinate points, such as: from (3,1) to (4,1). )
- Input
- The first line enters an integer n (0<n<=100), which indicates that there are n sets of test data;
Then n rows, each row has four integers a,b,c,d (0<=a,b,c,d<=8) representing the row, column, and end line of the starting point, respectively.
- Output
- The output is at least a few steps away.
- Sample input
-
1 5 1 6 7
- Sample output
-
1211
Topic Analysis:
Recursive function can be used in the backtracking method;
AC Code:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h>int x,y,ex,ey,step =0,min=10000;int map[9][9]={ 1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1, 1,0,0,1,1,0,0,0,1, 1,0,1,0,1,1,0,1,1, 1,0,0,0,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,0,0,0,1, 1,1,1,1,1,1,1,1,1};void Fun (int x,int y,int step,int &min) {if (X==ex&&y==ey) {if (step<min) {min= Step;} return;} Map[x][y]=1; if (map[x-1][y]==0&&step+1<min) {fun (x-1,y,step+1,min); map[x-1][y]=0;} if (map[x+1][y]==0&&step+1<min) {fun (x+1,y,step+1,min); map[x+1][y]=0;} if (map[x][y-1]==0&&step+1<min) {fun (x,y-1,step+1,min); map[x][y-1]=0;} if (map[x][y+1]==0&&step+1<min) {fun (x,y+1,step+1,min); map[x][y+1]=0;}} int main () {int t;scanf ("%d", &t), while (t--) {scanf ("%d%d%d%d", &x,&y,&ex,&ey); fun (x,y,0,min); map[x][y]=0;printf ("%d\n", Min);} return 0;}
Code Analysis:
1. DPS function in the form of: Fun (x, y, step, &min);
X, y indicates the current state, step indicates the number of steps to go to x, y, min record the shortest steps, ' & ' means address arithmetic, can save the results, record data;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Num 37:nyoj:0058 Minimum steps [backtracking method]