kuangbin系列【简单搜索】

poj-1321棋盘问题【bfs/回溯】
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 36385   Accepted: 17950

Description

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。

Input

输入含有多组测试数据。 
每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n 
当为-1 -1时表示输入结束。 
随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。 

Output

对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。

Sample Input

2 1
#.
.#
4 4
...#
..#.
.#..
#...
-1 -1

Sample Output

2
1

 

 【分析】:建议学习回溯的时候对N皇后还有N皇后的变式好好学习一下,类N皇后真是学习回溯非常好的例题。

如在第i行第j列,遇到'#'号。那么接下来的处理就有两种情况了。
第一种:把i,j放入到一个数组C中,然后继续向第i+1行进行搜索,直到找到m个位置或者到了棋盘的边界
另一种:不选择第i行第j列的位置,然后继续向第i+1行进行搜索,直到找到m个位置或者到了棋盘的边界

【代码】:
#include <cmath>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <set>
#include <map>
#include <list>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <string>
#include <vector>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
#pragma comment(linker, "/STACK:102400000,102400000")
#define Abs(x) ((x^(x >> 31))-(x>>31))
#define Swap(a,b) (a^=b,b^=a,a^=b)
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define EPS 1e-8
#define MOD 1000000007
#define max_ 505
#define maxn 200002

using namespace std;

int n,m;
char s[10][10];//表示棋盘  
int c[10];//表示每一列有没有摆放过棋子
int tot,cnt;

void dfs(int cur)//cur表示当前所在行
{
    if(cnt == m)//cnt表示当前所摆放棋子数目
    {
        tot++;
        return ;
    }

    if(cur >= n)//超出搜索范围
        return ;

    for(int j=0;j<n;j++)
    {
        if(!c[j] && s[cur][j]=='#')//空白处并且还没有摆放棋子
        {
            c[j]=1;
            cnt++;
            dfs(cur+1);//搜索下一行
            c[j]=0;//标记清除
            cnt--;
        }
    }
    dfs(cur+1);//如果当前行没有可以摆放的位置 或者cnt已经等于m 但是还没有搜索完整个棋盘 将要继续搜索下一行  
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        if(n==-1&&m==-1) break;
        memset(c,0,sizeof(c));//将标记初始化为0  
        tot=cnt=0;
        for(int i=0;i<n;i++)
        {
            scanf("%s",&s[i]);
        }
        dfs(0);
        printf("%d
",tot);
    }
}
View Code

 


POJ - 2251 Dungeon Master 【三维dfs】

Description 
You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.

Is an escape possible? If yes, how long will it take? 
Input 
The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size). 
L is the number of levels making up the dungeon. 
R and C are the number of rows and columns making up the plan of each level. 
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a ‘#’ and empty cells are represented by a ‘.’. Your starting position is indicated by ‘S’ and the exit by the letter ‘E’. There’s a single blank line after each level. Input is terminated by three zeroes for L, R and C. 

Output 
Each maze generates one line of output. If it is possible to reach the exit, print a line of the form 
Escaped in x minute(s).

where x is replaced by the shortest time it takes to escape. 
If it is not possible to escape, print the line 
Trapped!

Sample Input

3 4 5
S....
.###.
.##..
###.#

#####
#####
##.##
##...

#####
#####
#.###
####E

1 3 3
S##
#E#
###

0 0 0

Sample Output

Escaped in 11 minute(s).
Trapped!

 【题意】:给出一三维空间的地牢,要求求出由字符'S'到字符'E'的最短路径

  移动方向可以是上,下,左,右,前,后,六个方向

  每移动一次就耗费一分钟,要求输出最快的走出时间。

  不同L层的地图,相同RC坐标处是连通的

 【代码】:

#include <cmath>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <set>
#include <map>
#include <list>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <string>
#include <vector>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
#pragma comment(linker, "/STACK:102400000,102400000")
#define Abs(x) ((x^(x >> 31))-(x>>31))
#define Swap(a,b) (a^=b,b^=a,a^=b)
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define EPS 1e-8
#define MOD 1000000007
#define max_ 505
#define maxn 200002

using namespace std;

int n,m,k,x,y,z,sx,sy,sz,ex,ey,ez;
char s[35][35][35];//表示棋盘
int vis[35][35][35];//表示每一列有没有摆放过棋子
int dir[6][3]={ {0,0,1},{0,0,-1},{-1,0,0},{1,0,0},{0,-1,0},{0,1,0} };

struct node
{
    int x,y,z,step;
};

int check(int x,int y,int z)
{
    if(x<0 || y<0 || z<0 || x>=k || y>=n || z>=m)
        return 1;
    else if(s[x][y][z] == '#')
        return 1;
    else if(vis[x][y][z])
        return 1;
    return 0;
}


int bfs()
{
    //初始化
    node a,tmp; queue<node> q;
    a.x = sx,a.y = sy,a.z = sz,a.step = 0;
    vis[sx][sy][sz]=1;

    q.push(a);

    while(!q.empty())
    {
        a=q.front();
        q.pop();
        if(a.x==ex && a.y==ey && a.z==ez)
            return a.step;

        for(int i=0;i<6;i++)
        {
            tmp = a;
            tmp.x=a.x+dir[i][0];
            tmp.y=a.y+dir[i][1];
            tmp.z=a.z+dir[i][2];
            if(check(tmp.x,tmp.y,tmp.z))
                continue;
            vis[tmp.x][tmp.y][tmp.z]=1;
            tmp.step=a.step+1;
            q.push(tmp);
        }
    }
    return 0;
}

int main()
{
    int i,j,r;
    while(scanf("%d%d%d",&k,&n,&m),n+m+k)
    {
        for(i = 0; i<k; i++)
        {
            for(j = 0; j<n; j++)
            {
                scanf("%s",s[i][j]);
                for(r = 0; r<m; r++)
                {
                    if(s[i][j][r] == 'S')
                    {
                        sx = i,sy = j,sz = r;
                    }
                    else if(s[i][j][r] == 'E')
                    {
                        ex = i,ey = j,ez = r;
                    }
                }
            }
        }
        memset(vis,0,sizeof(vis));
        int ans;
        ans = bfs();
        if(ans)
            printf("Escaped in %d minute(s).
",ans);
        else
            printf("Trapped!
");
    }

    return 0;
}
View Code

 


 

poj 3278 【一维bfs】

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 71899   Accepted: 22632

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points - 1 or + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N and K

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

Source

【分析】:给出2个数n和k,问从n经过+1或者-1或者*2能到达k的最小步数。分3个方向的一维BFS。注意n可以比k大,这时只有-1一种办法可以从n到达k,直接减就行了,还有要注意边界的判断。
【代码】:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>

using namespace std;
#define maxn 100010

queue<int> q;
int n,k;
int vis[maxn];
int step[maxn];//步数数组装总步数

int bfs(int n,int k)
{
    ///////////////////////////
    memset(vis,0,sizeof(vis));
    int now,nxt;
    step[n]=0;//初始化步数为0
    vis[n]=1;//标记最开始的节点被访问
    q.push(n);//起始节点入队
    ///////////////////////////

    while(!q.empty())
    {
        now=q.front();
        q.pop();

        //if(nxt==k) return step[nxt];

        for(int i=0;i<3;i++)              //遍历
        {
            if(i==0)      nxt=now+1;
            else if(i==1) nxt=now-1;
            else if(i==2) nxt=now*2;     //顺序无关

            if(nxt<0||nxt>maxn) continue;//越界

            if(!vis[nxt])                //判重
            {
                vis[nxt]=1;
                step[nxt]=step[now]+1;
                q.push(nxt);
            }

            if(nxt==k) return step[nxt];//找到

        }
    }
}
int main()
{
    int n,k;
    scanf("%d%d",&n,&k);
    if(n>=k)
        printf("%d
",n-k);
    else
        printf("%d
",bfs(n,k));
    return 0;
}
一维BFS

Find The Multiple  POJ - 1426

Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.

Input

The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.

Output

For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.

Sample Input

2
6
19
0

Sample Output

10
100100100100100100
111111111111111111

 【题意】:输入一个整数,求大于等于这个整数的且满足条件的最小值 ,条件是这个整数能整出输入的整数,且这个整数只能包括0和1。

【分析】:可以BFS/DFS。这题搜索的方向有两个而且它的下界不好确定。所以可以用迭代加深搜索的技巧.用一个maxed控制搜索的下界。或者根据无符号整型确定深度最多为19.起点必须为1.

【代码】:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<math.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>

using namespace std;
#define LL long long
int n;
LL now;
void bfs(int ans)
{
    queue<LL> q;
    q.push(ans);
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        if(now%n==0)
        {
            cout<<now<<endl;
            return ;
        }
        q.push(now*10);
        q.push(now*10+1);
    }
}
int main()
{
    while(cin>>n,n)
    {
        bfs(1);
    }
    return 0;
}
BFS
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<math.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>

using namespace std;
#define ULL unsigned __int64
int f,n;
void dfs(ULL now,int s)
{
    if(f) return;// 放在最前面
    if(now%n==0)
    {
        cout<<now<<endl;
        f=1;
        return;
    }
    if(s==19) return;  //因为unsigned __int64的范围是-9223372036854775808~9223372036854775807(10^19)与0~18446744073709551615(10^20)
                       //为防止超出范围,循环深度应小于20
    dfs(now*10,s+1);       //当前数字有两种选择方案,即下一个数选1或选0
    dfs(now*10+1,s+1);
}
int main()
{
    while(cin>>n,n)
    {
         f=0;
         dfs(1,0);//首位数字必须为1
    }
}
DFS
#include<cstdio>
#include<algorithm>
using namespace std;
long long n,maxed;
long long s;
bool flag;
void dfs(long long i,int step)
{
    if(flag) return;
    if(step>=maxed) return;//当当前的递归深度达到上界后就return;
    if(i%n==0)
    {
        printf("%lld
",i);
        flag=true;
        return;
    }
    dfs(i*10,step+1);
    dfs(i*10+1,step+1);
}

int main()
{
    while(~scanf("%d",&n)&&n)
    {
        flag=false;
        for(maxed=1;;++maxed)//让第一个搜不到就结束
        {
            if(flag)
                break;
            dfs(1,0);
        }
    }
}
DFS-迭代加深
原文地址:https://www.cnblogs.com/Roni-i/p/7798527.html