1153. 马的周游问题

来源:互联网 发布:淘宝网人工投诉电话 编辑:程序博客网 时间:2024/05/18 01:17
#include <iostream>#include <vector>#include <memory.h>#include <algorithm>using namespace std;/*   重点1:递归两种方式,一种类似本例,判断条件返回true和false;          另外一个类似阶乘递归,return 1; or return n*(n-1)! */ //变量:记录点坐标,totaltonext记录该点下一步可以走的方向总数 struct point{    int x;    int y;    int totaltonext; };//变量:记录某点是否已经走过,走过为1,未走为0  int board[10][10];//变量:记录八个方向  int move_x[] = {-1, -1, -2, -2, 1, 1, 2, 2};int move_y[] = {-2, 2, 1, -1, 2, -2, 1, -1}; bool isfind;//变量:记录走过的点位置 int path[100];bool dfs(point, int);bool isvalue(point );bool cmp(point , point ); int main(){    int n;    point p;          //freopen("C:\\Users\\Haojian\\Desktop\\test.txt", "r", stdin);    while (cin >> n && n != -1)    {        isfind = false;        //重点2:memset函数,#include <memory.h>         memset(board, 0, 10*10*sizeof(int));        p.x = (n - 1) / 8 + 1;        p.y = n - ((p.x-1) * 8);        //p.num = 1;    //    path[p.num-1] = n;        path[0] = n;        board[p.x][p.y] = 1;        dfs (p, 1);     }    return 0;}  bool dfs (point p, int current){    point n;      //重点3:递归结束判断条件     if (current == 64)    {        for (int i = 0; i < 63; i++)            cout << path[i] << " ";        cout << path[63];        cout << endl;        return true;    }    else    {        vector<point> tmp;        for (int i = 0; i < 8; i++)        {            n.x = p.x + move_x[i];            n.y = p.y + move_y[i];            n.totaltonext = 0;                         if (isvalue(n))            {                                 point k;                for (int j = 0; j < 8; j++)                {                    k.x = n.x + move_x[j];                    k.y = n.y + move_y[j];                    if (isvalue(k))                        n.totaltonext++;                }                                     tmp.push_back(n);            }        }//计算下一个要找的点的扩展点         sort(tmp.begin(), tmp.end(), cmp);//按扩展点从小到大排序                //从扩展点小的开始搜索        //重点4:一直找到底,当没有找到时,返回false,并且返回上一层,继续深度优先搜索;        //       当找到时,返回基本条件的true,层层返回true;                  for (int i = 0; i < tmp.size(); i++)        {            board[tmp[i].x][tmp[i].y] = 1;            path[current] = (tmp[i].x - 1) * 8 + tmp[i].y;            if (dfs(tmp[i], current+1)) return true;            board[tmp[i].x][tmp[i].y] = 0;        }                       }     ////重点5:递归结束判断条件     return false;}//函数:用于排序,升序排序  bool cmp(point a, point b){    return a.totaltonext < b.totaltonext;}//函数:用于判断某点是否有效  bool isvalue(point n){    return (n.x >= 1 && n.x <= 8 && n.y >= 1 && n.y <= 8 && !board[n.x][n.y]);}

原创粉丝点击