zoukankan      html  css  js  c++  java
  • POJ 3009

    POJ 3009

    DFS

    这道题乍一看是 BFS 求最短路的模型

    但是因为题目中有一条规则,如果让冰球动起来必须要扔掉它旁边的石头

    When the stone stands still, you can make it moving by throwing it. You may throw it to any direction unless it is blocked immediately(Fig. 2(a)).

    因此这个图在搜索的过程是会动态改变的,而BFS是同时进行多种状态,每种状态相互独立才能使用

    DFS 每次只搜索一种状态,还可以进行回溯,所以对状态的改变都能应对

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    #define endl '
    '
    const int N = 50,INF = 0x3f3f3f3f;
    int g[N][N],n,m,ans;
    int dx[4] = {0,0,1,-1},dy[4] = {1,-1,0,0};
    bool check(int x,int y) {
        if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] != 1) return 1;
        else return 0;
    }
    void dfs(int x,int y,int step) {
        if(step > 10) return;// 如果超过 10步就停止
        for(int i = 0;i < 4; ++i) {
            int nx = x + dx[i],ny = y + dy[i];
            while(check(nx,ny)) {// 一直朝一个方向走
                while(check(nx,ny) && g[nx][ny] != 3) {// 如果没有碰到终点 且 没有碰到 石头 就继续走
                    nx += dx[i];
                    ny += dy[i];
                }
                if(g[nx][ny] == 3) { // 如果是终点就记录答案
                    ans = min(ans,step);// 取最小值
                    return ;
                }
                if(g[nx][ny] == 1) {// 如果是石头
                    g[nx][ny] = 0;// 把这块石头扔掉
                    dfs(nx - dx[i],ny - dy[i],step + 1);
                    // 石头前面一个地方才是冰球的位置,要减去这个方向向量,然后步数+1,继续dfs
                    g[nx][ny] = 1;// 回溯石头的状态
                }
            }
        }
    }
    int main() {
        ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
        while(cin >> m >> n && n && m) {
            int sx,sy;
            memset(g,0,sizeof g);
            ans = INF;
            for(int i = 0;i < n ; ++i) {
                for(int j = 0;j < m; ++j) {
                    cin >> g[i][j];
                    if(g[i][j] == 2) sx = i,sy = j;
                }
            }
            dfs(sx,sy,1);
            if(ans > 10) cout << "-1";
            else cout << ans;
            cout << endl;
        }
        return 0;
    }
    
  • 相关阅读:
    Java实现单链表的各种操作
    LintCode #452 删除链表中的元素
    前两天做项目遇到了sqlserver最大连接数 Max Pool Size 的问题
    Redis的应用场景
    说一说MVC的Authentication过滤(四)
    MVC中的下载文件及上传
    Python之高级特性
    说一说MVC的MenuCard(五)
    说一说MVC的CSRF(三)
    说一说MVC的控制器(二)
  • 原文地址:https://www.cnblogs.com/lukelmouse/p/12439006.html
Copyright © 2011-2022 走看看