zoukankan      html  css  js  c++  java
  • 迷宫 (BFS)

    《挑战程序设计》 P34

    第一次使用pair

    1.头文件:<utility>
    2.成员:mypair.first, mypair.second
    3.运算符:<、>、<=、>=、==、!=,其规则是先比较first,first相等时再比较second
    4.相关函数:make_pair 例如:p=make_pair(1,1); q.push(make_pair(1,1));

    #include <iostream>
    #include <utility>
    #include <cstdio>
    #include <queue>
    
    using namespace std;
    
    const int INF = 100000000;
    
    typedef pair<int, int> P;
    
    const int N = 100;
    
    char maze[N][N + 1];
    int n, m;
    int sx, sy;
    int gx, gy;
    
    int d[N][N]; 			//记录到各个位置的最短距离
    
    int dx[4] = {-1, 0, 1, 0};
    int dy[4] = {0, 1, 0, -1};
    
    int bfs()
    {
    	queue<P> que;
    	for (int i = 0; i < n; ++i)
    		for (int j = 0; j < m; ++j)
    			d[i][j] = INF;
    	que.push(P(sx, sy));
    	d[sx][sy] = 0;
    
    	while (que.size()) {
    		P p = que.front();
    		que.pop();
    		if (p.first == gx && p.second == gy) break;
    
    		for (int i = 0; i < 4; ++i) {
    			int nx = p.first + dx[i];
    			int ny = p.second + dy[i];
    			if (nx < n && nx >= 0 && ny < m && ny >= 0 &&
    					maze[nx][ny] != '#' && d[nx][ny] == INF) {
    				d[nx][ny] = d[p.first][p.second] + 1;
    				que.push(P(nx, ny));
    			}
    		}
    	}
    	return d[gx][gy];
    }
    
    void solve()
    {
    	scanf("%d%d", &n, &m);
    	for (int i = 0; i < n; ++i) {
    		getchar();
    		for (int j = 0; j < m; ++j) {
    			scanf("%c", &maze[i][j]);
    			if (maze[i][j] == 'S') sx = i, sy = j;
    			if (maze[i][j] == 'G') gx = i, gy = j;
    		}
    	}
    	int res = bfs();
    	printf("%d
    ", res);
    }
    
    int main()
    {
        solve();
        return 0;
    }
    
    /****************
    Input:
    10 10
    #S######.#
    ......#..#
    .#.##.##.#
    .#........
    ##.##.####
    ....#....#
    .#######.#
    ....#.....
    .####.###.
    ....#...G#
    
    Output:
    22
    *****************/
    

      

  • 相关阅读:
    获取Enum枚举值描述的几法方法
    c# 快速验证代理IP是否有用
    解析JSON对象与字符串之间的相互转换
    MVC4相关Razor语法以及Form表单(转载)
    MVC4数据注解和验证
    C#在Json反序列化中处理键的特殊字符
    EasyUI 兼容 IE6 方法总结
    uploadify在IE6下的问题
    Could not resolve dependencies for project, Failed to read artifact descriptor for
    shell 文本单词计数
  • 原文地址:https://www.cnblogs.com/wenruo/p/4707687.html
Copyright © 2011-2022 走看看