[dfs]POJ3050 Hopscotch

簡單題,在5 * 5的方格里跳各自子,起點是任意位置。將跳過的數連起來組成一個6位數(可能前導零),問一共能組成多少個數字?

當前的狀態可以定義爲當前位置、當前數字長度、當前數字這三個要素,利用狀態轉移dfs即可遍歷所有情況。

對於當前數字的儲存,可以用數組或者vector來保存,因爲只有6位數,所以直接用int也是可以的,關於判重的方法,STL大法set可以輕鬆地滿足要求。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<set>
#include<vector>
#include<map>
#include<string>
#include<iostream>
#include<queue>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
int maze[10][10];
set<int> ms;
int dx[] = {0,0,1,-1};
int dy[] = {-1,1,0,0};

//當前位置,當前數字長度,當前數字
void dfs(int x,int y,int len,int num) //也可以不記錄當前數字,用數組或者vector來保存
{
    if (len==6)
    {
        ms.insert(num);
        return ;
    }
    for(int i = 0;i<4;i++)
    {
        int nx = x+dx[i];
        int ny = y+dy[i];
        if(nx>0 && nx <=5 && ny>0 && ny<=5)
            dfs(nx,ny,len+1,num*10 + maze[nx][ny]);
    }
}

int main()
{
    for(int i = 1;i <= 5; i++)
        for(int j = 1; j <= 5; j++)
            scanf("%d",&maze[i][j]);

    for(int i = 1;i<=5;i++)
        for(int j = 1;j<=5;j++)
            dfs(i,j,1,maze[i][j]);

    printf("%d\n",ms.size());
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章