NYOJ题目58-最少步数(搜索)

来源:互联网 发布:excel筛选重复数据函数 编辑:程序博客网 时间:2024/05/01 22:59

描述
这有一个迷宫,有0~8行和0~8列:

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表示道路,1表示墙。

现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?

(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)

输入
第一行输入一个整数n(0

#include <iostream>#include <algorithm>using namespace std;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};int book[9][9];int step;int Min;int next[4][2] = {{0,1},{-1,0},{0,-1},{1,0}};void dfs(int x, int y,int endx, int endy, int step){    if(x == endx && y == endy){        if(step < Min)            Min = step;        return ;    }    for(int k = 0 ; k < 4; k++){        int tx = x + next[k][0];        int ty = y + next[k][1];        if(tx < 0 || tx > 8 || ty < 0 || ty > 8)            continue;        if(Map[tx][ty] == 0 && book[tx][ty] == 0){            book[tx][ty] = 1;            dfs(tx,ty,endx,endy,step + 1);            book[tx][ty] = 0;        }    }    return ;}int main(){    int N;    cin >> N;    int sx,sy,ex,ey;    while(N--){        cin >> sx >> sy >> ex >> ey;        for(int i = 0 ; i < 9; i++)            for(int j = 0; j < 9; j++)                book[i][j] = 0;        step = 0;        Min = 99999999;        book[sx][sy] = 1;//起始点标记,这个忘了         dfs(sx,sy,ex,ey,0);        cout << Min << endl;    }    return 0;}
0 0
原创粉丝点击