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;
    }
  • 相关阅读:
    Oracle 常用函数备查
    apt-get/dpkg常用指令备查
    vmware下虚拟机不能上网问题解决
    [转]JAVA并发编程学习笔记之Unsafe类
    solaris 下查看某程序所开端口
    java 守护线程
    Java实现非法访问异常
    Java使用ListIterator逆序ArrayList
    Java实现Map集合二级联动
    Java使用String类格式化当前日期
  • 原文地址:https://www.cnblogs.com/tanhehe/p/3225925.html
Copyright © 2011-2022 走看看