zoukankan      html  css  js  c++  java
  • 图论--走出泥潭

    题目描述:

    探险队要穿越泥潭,必须选择可踩踏的落脚点。可是泥潭面积很大,落脚点又实在少得可怜,一不小心就会深陷泥潭而无法脱身。侦查员费尽周折才从老乡手里弄到了一份地图,图中标出了落脚点的位置,而且令人震惊的是:泥潭只有一条穿越路线,且对于nxm的地图,路线长度为n+m-1!请编程为探险队找出穿越路线。

    输入描述:

    两个整数n和m,表示泥潭的长和宽。下面n行m列表示地形(0 表示泥潭,1 表示落脚点)

    输出描述:

    用坐标表示穿越路线,坐标之间用>分隔

    样例输入:

    6 9

    1 1 1 0 0 0 0 0 0

    0 0 1 1 1 0 0 0 0

    0 0 0 0 1 0 0 0 0

    0 0 0 0 1 1 0 0 0

    0 0 0 0 0 1 1 1 1

    0 0 0 0 0 0 0 0 1

    样例输出:

    (1,1)>(1,2)>(1,3)>(2,3)>(2,4)>(2,5)>(3,5)>(4,5)>(4,6)>(5,6)>(5,7)>(5,8)>(5,9)>(6,9)

    这题困扰了好几天之前把他当成了BFS发现行不通,今天用DFS写了一遍算是对这个的复习吧

    下面附上本校oj的AC代码:

    #include<iostream>
    #include<cstring>
    using namespace std;
    const int N=101;
    int map[N][N];
    int n,m;
    struct point{
        int l,r;
    }node[N];//结构体数组用来存储路径
    int ans;
    void DFS(int x,int y)//这是深度优先搜索实现过程,本质就是一个递归的过程
    {
        if(x==n&&y==m)
        {
            for(int i=1;i<ans;i++)
            cout<<"("<<node[i].l<<","<<node[i].r<<")>";
            cout<<"("<<x<<","<<y<<")"<<endl;
    //        cout<<ans<<endl;
        }
        else{
            if(map[x][y]==1&&x<=n&&y<=m)
            {
                node[ans].l=x;
                node[ans].r=y;
                ans++;
                DFS(x+1,y);
                DFS(x,y+1);
            }
        }
    }
    int main()
    {
        while(cin>>n>>m)
        {
            ans=1;
            memset(map,0,sizeof(map));
            for(int i=1;i<=n;i++)
                for(int j=1;j<=m;j++)
                cin>>map[i][j];
            DFS(1,1);    
        }
        return 0;
    }

  • 相关阅读:
    学习ios键盘和textfield之间操作体会
    关于Cannot assign to 'self' outside of a method in the init family解决方法
    "this class is not key value coding-compliant for the key ..."问题的解决
    在编译oc中protocol时出现的错误
    关于oc中出现的typedef的用法/定义函数指针
    VC++、MFC、COM和ATL的区别
    leetcode : Spiral Matrix II
    leetcode : Length of Last Word [基本功]
    leetcode : triangle
    leetcode : Insert Interval
  • 原文地址:https://www.cnblogs.com/acmblog/p/9481082.html
Copyright © 2011-2022 走看看