码迷,mamicode.com
首页 > 编程语言 > 详细

poj 3050 地图5位数问题 dfs算法

时间:2018-08-02 11:20:37      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:poj   数加   pac   size   space   思路   上下左右   dfs   for   

题意:一个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\n", results.size());
    return 0;
}

 

poj 3050 地图5位数问题 dfs算法

标签:poj   数加   pac   size   space   思路   上下左右   dfs   for   

原文地址:https://www.cnblogs.com/xuxiaojin/p/9405595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!