zoukankan      html  css  js  c++  java
  • poj 3050 地图5位数问题 dfs算法

    题意:一个5*5地图上面,从任意位置上下左右跳五次,组成一个数。问:不重复的数有多少个?

    思路:dfs

    1. 从任意位置跳5次,说明每个位置都需要遍历。
    2. 组成一个数:number*10+map[dx][dy]
    3. 不重复的数字,用set(集合)来存储
    4. 只需要每次跳的时候步数加1,并且可以跳的位置,只要不超过范围就可以,即一个位置可以重复跳

    解决问题的代码:

    #include <iostream>
    #include <cstdio>
    #include <set>
    using namespace std;
    int map[5][5];
    set<int> results;
    const int dir[4][2]
    {
        { 0,1 },{ 0,-1 },{ 1,0 },{ -1,0 }
    };
    void dfs(const int& x, const int& y, const int& step, const int& number)
    {
        if (step == 5)
        {
            results.insert(number);
            return;
        }
        for (int i = 0; i < 4; i++)
        {
            int dx = x + dir[i][0];
            int dy = y + dir[i][1];
            if (dx >= 0 && dx < 5 && dy >= 0 && dy < 5)
                dfs(dx, dy, step + 1, number * 10 + map[dx][dy]);
        }
    }
    int main()
    {
        for (int i = 0; i < 5; i++)
            for (int j = 0; j < 5; j++)
                scanf("%d", &map[i][j]);
        for (int i = 0; i < 5; i++)
            for (int j = 0; j < 5; j++)
                dfs(i, j, 0, map[i][j]);
        printf("%d
    ", results.size());
        return 0;
    }
    君子知命不惧,自当日日自新
  • 相关阅读:
    第二次结对编程作业
    团队项目-需求分析报告
    团队项目-选题报告
    Git安装
    VI编辑,backspace无法删除解决方法
    VM虚拟机,Linux系统安装tools过程遇到 what is the location of the “ifconfig” program
    Ubuntu安装mysql
    Linux配置Tomcat
    Linux配置JDK
    鸡汤
  • 原文地址:https://www.cnblogs.com/xuxiaojin/p/9405595.html
Copyright © 2011-2022 走看看