来自别人的:http://blog.csdn.net/alalalalalqp/article/details/9155419
下面是我自己的】=:
DFS:
#include <iostream>
#include <string.h>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstdio>
#define MAXN 100
using namespace std;
char a[MAXN+5][MAXN+5];
int k,n,m;
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
bool dfs(int x,int y)
{
if(a[x][y]=='E')
return true;
if(a[x][y]=='*')
return true;
if(a[x][y]>='0'&&a[x][y]<='9')
if(a[x][y]-'0'>k)
return false;
a[x][y]='#';
for(int i=0;i<4;i++)
{
int xx=x+dx[i];
int yy=y+dy[i];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&a[xx][yy]!='#')
if(dfs(xx, yy))
return true;
}
return false;
}
int main()
{
int T,sx,sy;
while(~scanf("%d",&T))
{
while(T--)
{
scanf("%d%d%d",&k,&n,&m);
getchar();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%c",&a[i][j]);
if(a[i][j]=='S')
{
sx=i;
sy=j;
}
}
getchar();
}
if(dfs(sx,sy)) printf("No\n");
else printf("Yes\n");
}
}
return 0;
}
BFS:
#include <iostream>
#include <string.h>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstdio>
#define MAXN 200000
using namespace std;
int n;
struct Node
{
int x,d;
};
bool a[MAXN+5];
Node temp;
queue<Node> q;
int bfs(int k)
{
memset(a, false, sizeof(a));
while(!q.empty()) q.pop();
temp.x=k;temp.d=0;
q.push(temp);
while(!q.empty())
{
temp=q.front();q.pop();
int x=temp.x;
int d=temp.d;
if(a[x]) continue;
if(x==n) return d;
a[x]=true;
if(x*2<2*n&&!a[2*n])
{
temp.x=x*2;
temp.d=d+1;
q.push(temp);
}
if(x>1&&!a[x-1])
{
temp.x=x-1;
temp.d=d+1;
q.push(temp);
}
if(x+1<=n&&!a[x+1])
{
temp.x=x+1;
temp.d=d+1;
q.push(temp);
}
}
return 0;
}
int main()
{
int T;
while(~scanf("%d",&T))
{
while(T--)
{
scanf("%d",&n);
printf("%d\n",bfs(1));
}
}
return 0;
}