zoukankan      html  css  js  c++  java
  • [算法] BFS : poj 2312 Battle City 示例

    纪念第一次用  “优先队列”, 第一次知道 “方向数组” ! BFS : 谁出队就找谁的邻接点访问之并入队!
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <cstdlib>
    #include <cstdio>
    #include <cmath>
    #include <vector>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <bitset>
    #include <list>
    #include <map>
    #include <set>
    #include <iterator>
    #include <algorithm>
    #include <functional>
    #include <utility>
    #include <sstream>
    #include <climits>
    #include <cassert>
    #define BUG puts("here!!!");
    
    using namespace std;
    const int N = 305;
    struct Point {
    	int x, y;
    	int steps;
    };
    char mmap[N][N];
    int n, m;
    int dx[] = {0, 0, -1, 1};
    int dy[] = {-1, 1, 0, 0};
    bool ok(int x, int y) {
    	return (x >= 0 && x < m && y >= 0 && y < n);
    }
    Point you, tag;
    bool operator < (const Point &a, const Point &b) {
    	return a.steps > b.steps;
    }
    int bfs() {
        priority_queue<Point> Q;
    	Q.push(you);
    	Point t, tmp;
    	int xx, yy;
    	while(!Q.empty()) {
    		t = Q.top(); Q.pop();
    		for(int i = 0; i < 4; i++) {
    			xx = t.x + dx[i];
    			yy = t.y + dy[i];
    			if(!ok(xx, yy) || mmap[xx][yy] == 'R' || mmap[xx][yy] == 'S') {
    				continue;
    			}
    			if(xx == tag.x && yy == tag.y) return t.steps + 1;
    			tmp.x = xx;
    		    tmp.y = yy;
    			if(mmap[xx][yy] == 'B') {
    				tmp.steps = t.steps + 2;
    			}
    			else tmp.steps = t.steps + 1;
    			mmap[xx][yy] = 'R';
    			Q.push(tmp);
    		}
    	}
    	return -1;
    }
    int main() {
    	while(scanf("%d%d", &m, &n), m|n) {
    		for(int i = 0; i < m; i++) {
    			for(int j = 0; j < n; j++) {
    				cin >> mmap[i][j];
    				if(mmap[i][j] == 'Y') {
    					you.x = i;
    					you.y = j;
    					you.steps = 0;
    				}
    				else if(mmap[i][j] == 'T') {
    					tag.x = i, tag.y = j;
    				}
    			}
    		}
    		printf("%d\n", bfs());
    	}
    	return 0;
    }
    

  • 相关阅读:
    HDU2036 计算多边形的面积
    poj 3648 线段树成段更新
    线段树基本知识
    计算几何基本模板
    最长递增子序列问题—LIS
    poj 2503
    Python基础(5)_字符编码、文件处理
    Python基础(4)_字典、集合、bool值
    Python基础(3)_可变对象与不可变对象、列表、元祖和字典
    流程控制练习
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787176.html
Copyright © 2011-2022 走看看