zoukankan      html  css  js  c++  java
  • POJ3009 Curling 2.0(DFS)

    题目链接

    分析:

    本题BFS A不了。

    00100

    00001

    01020

    00000

    00010

    00010

    00010

    00010

    00030

    对于这样的数据,本来应当是 5 步,但bfs却 4 步。具体原因可以仔细看一下上面的样例。

    应当dfs穷举所有的可能,找出最短的。

    #include <iostream>
    #include <cstdio>
    #include <queue>
    
    using namespace std;
    
    const int maxn = 23;
    const int INF = (1<<29);
    
    int dx[] = {1, -1, 0, 0};
    int dy[] = {0, 0, -1, 1};
    
    int h, w, G[maxn][maxn], min_step;
    
    void dfs(int x, int y, int step) {
        int nx, ny;
    
        if(step >= 10) return ;
    
        for(int d=0; d<4; d++) {
            nx = x; ny = y;
            nx = x+dx[d];
            ny = y+dy[d];
    
            if(nx < 0 || ny < 0 || nx >= h || ny >= w) continue ;
            if(G[nx][ny] == 1) continue;    //靠着墙
    
            while(!(G[nx][ny] == 1 || G[nx][ny] == 3)) {
                nx += dx[d];
                ny += dy[d];
                if(nx < 0 || ny < 0 || nx >= h || ny >= w) break;
            }
    
            if(nx < 0 || ny < 0 || nx >= h || ny >= w) continue;    //这个判断有必要
    
            if(G[nx][ny] == 3) {    //终点
                min_step = min(min_step, step+1);
            }
            else if(G[nx][ny] == 1){  //
                G[nx][ny] = 0;
                dfs(nx-dx[d], ny-dy[d], step+1);
                G[nx][ny] = 1;
            }
        }
    }
    
    int main(){
        int sx, sy;
    
        while(scanf("%d%d", &w, &h) == 2) {
            if(w == 0 && h == 0) break;
    
            min_step = INF;
    
            for(int i=0; i<h; i++) {
                for(int j=0; j<w; j++) {
                    scanf("%d", &G[i][j]);
                }
            }
    
            for(int i=0; i<h; i++) {
                for(int j=0; j<w; j++) {
                    if(G[i][j] == 2) {
                        sx = i; sy = j;
                    }
                }
            }
    
            dfs(sx, sy, 0);
    
            if(min_step != INF) {
                printf("%d
    ", min_step);
            }
            else printf("-1
    ");
        }
    
        return 0;
    }
  • 相关阅读:
    ASP.NET MVC 页面重定向
    Linux用户管理
    linux开机、重启和用户注销
    vi和vim
    Mac 与 Linux服务器上传下载
    linux 文件体系
    linux 常用命令及异常处理
    单独使用ueditor的图片上传功能,同时获得上传图片地址和缩略图
    mybatis oracle 插入自增记录 获取主键值 写回map参数
    MyBatis SpringMVC映射配置注意
  • 原文地址:https://www.cnblogs.com/tanhehe/p/3225925.html
Copyright © 2011-2022 走看看