codevs 1010 过河卒 dfs

题目:codevs1010 过河卒


思路:感觉没啥好说的,一看到题就想到了dfs(深度优先搜索),按理说bfs(广度优先搜索也可以做出来),不过我一次就过了(这感觉真爽),就没尝试bfs;


代码如下:


#include
#include
using namespace std;
int a[25][25];
int bx,by;
int cx,cy;
int count = 0;
int dx[2] = {1,0};
int dy[2] = {0,1};
bool check(int x,int y)
{
	if(x == bx&&y == by)
	{
		count++;
		return true;
	}
	else return false;
}
bool can_Step(int x,int y)
{
	if(x<=bx&&y<=by)
	{
		return true;
	}
	else return false;
}
void dfs(int ax,int ay)
{
	if(check(ax,ay))
	{
		return;
	}
	else 
	{
		for(int i = 0;i < 2;i++)
		{
			int newx = ax+dx[i];
			int newy = ay+dy[i];
			if(can_Step(newx,newy)&&!a[newx][newy])
			{
				a[newx][newy] = 1;
				dfs(newx,newy);
				a[newx][newy] = 0;
			}
		}
	}
}

int main()
{
	memset(a,0,sizeof(a));
	cin >> bx >> by >> cx >> cy;
	a[cx][cy] = 1;
	a[cx+2][cy+1] = 1;
	a[cx+2][cy-1] = 1;
	a[cx-2][cy+1] = 1;
	a[cx-2][cy-1] = 1;
	a[cx-1][cy-2] = 1;
	a[cx-1][cy+2] = 1;
	a[cx+1][cy-2] = 1;
	a[cx+1][cy+2] = 1;
	dfs(0,0);
	cout << count;
	return 0;
 } 


还有一种dp(动态规划)的方法,也挺简单的;

代码如下:

#include
#include
using namespace std;
int a[25][25];
int b[25][25];
int bx,by;
int cx,cy;
int main()
{
	memset(a,0,sizeof(a));
	cin >> bx >> by >> cx >> cy;
	a[cx][cy] = 1;
	a[cx+2][cy+1] = 1;
	a[cx+2][cy-1] = 1;
	a[cx-2][cy+1] = 1;
	a[cx-2][cy-1] = 1;
	a[cx-1][cy-2] = 1;
	a[cx-1][cy+2] = 1;
	a[cx+1][cy-2] = 1;
	a[cx+1][cy+2] = 1;
	b[0][0] = 1;
	int i,j;
	for(i=1;i<=bx;i++)b[i][0]=(b[i-1][0]&&!a[i][0]);  
    for(j=1;j<=by;j++)b[0][j]=(b[0][j-1]&&!a[0][j]);  
    for(i=1;i<=bx;i++){
        for(j=1;j<=by;j++){
            if(!a[i][j])b[i][j]=b[i-1][j]+b[i][j-1]; 
		}
	}
	cout << b[bx][by]; 
	return 0;
 } 


ps:没有bug的感觉真好~~~

你可能感兴趣的:(自己的一些练习)