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;
    }
    
  • 相关阅读:
    c#FileStream文件读写(转)
    mvc Razor 视图中找不到 ViewBag的定义
    JS正则表达式验证账号、手机号、电话和邮箱
    jquery each循环,
    $.grep(array, callback, [invert])过滤,常用
    arguments 对象
    有关Select option 元素
    MVC零基础学习整理(一)
    根据年月日算出当前日期是星期几
    C# winfrom 模拟ftp文件管理
  • 原文地址:https://www.cnblogs.com/lukelmouse/p/12439006.html
Copyright © 2011-2022 走看看