• 25-最短步数(广搜)


    http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=58        

              最少步数

    时间限制:3000 ms  |  内存限制:65535 KB
    难度:4
     
    描述

    这有一个迷宫,有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<n<=100),表示有n组测试数据;
    随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
    输出
    输出最少走几步。
    样例输入
    2
    3 1  5 7
    3 1  6 7
    样例输出
    12
    11
    
    来源
    [苗栋栋]原创
    上传者
    苗栋栋
    思路:就是广搜,但要注意用一个数据记录已经搜所过的,否则放入队列太多导致超内存,还有注意每次结束清除对列,防止对后面的影响。
    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <queue>
    using namespace std;
    typedef struct node{
    	int x;
    	int y;
    }node;
    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 visit[9][9]; //记忆 
    int bu[9][9]; 
    int a, b, c, d;
    //int bu = 0;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {-1, 1, 0, 0};
    queue <node> point;
    
    int dfs(int x, int y, int c, int d){
    	node sorce;
    	sorce.x = x, sorce.y = y;
    	point.push(sorce);
    	while(!point.empty()){
    		node p;
    		p = point.front();
    		point.pop();
    		if(p.x == c && p.y == d){
    //			bu++;
    			while(!point.empty()){  //每次结束,要清空队列 
    				point.pop();
    			}
    			return bu[p.x][p.y];
    		}
    		for(int i = 0; i < 4; i++){
    			int xx = p.x + dx[i];
    			int yy = p.y + dy[i];
    			if(xx >= 0 && xx <= 8 && yy >= 0 && yy <= 8 ){
    				if(map[xx][yy] == 0 && visit[xx][yy] == 0){ //加一个辅助数组,记忆已扫描过的 
    					visit[xx][yy] = 1;
    					node dq;
    					dq.x = xx, dq.y = yy;
    					point.push(dq);
    					bu[xx][yy] = bu[p.x][p.y] + 1;  //广搜,记录每一圈的圈数 
    				}
    			}		
    		}		
    	}
    	return -1; 
    }
    
    int main(){
    	int t;
    	cin >> t;
    	while(t--){
    		memset(bu, 0, sizeof(bu));
    		memset(visit, 0, sizeof(visit));
    		cin >> a >> b >> c >> d;
    		cout << dfs(a, b, c, d) << endl;		
    	}
    	
    	return 0;
    } 
    

      

  • 相关阅读:
    day29 作业
    day 29 线程
    day28 进程
    day27 服务端 和客户端
    day26 作业
    day26 网络编程
    java基础 反射
    python 计时
    mongodb 批量插入唯一索引冲突
    js hook
  • 原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/8428883.html
Copyright © 2020-2023  润新知