挑战第二章 poj 3009 水题DFS

题目给出剪枝条件10步就剪。。直接暴力


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cmath>
#include <vector>
#include <bitset>
#include <bitset>
#include <ctime>
using namespace std;

#define LL long long
#define SZ(v) ((int)(v).size())  
#define FOR(i,st,ed)	for((i)=(st);(i)!=(ed);++(i))
#define REP(i,ed)	FOR(i,0,ed)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)  
#define REPE(i,n) FORE(i,0,n)  
#define FORSZ(i,a,v) FOR(i,a,SZ(v))  
#define REPSZ(i,v) REP(i,SZ(v))  

void nextInt(int &x)
{
	scanf("%d", &x);
}

void nextInt(int &x, int &y)
{
	scanf("%d%d", &x, &y);
}

int g[30][30];
int nowx, nowy;
int n, m;
int xbegin,xend,ybegin,yend;

void init()
{
	memset(g,0,sizeof(g));
	int i,j;
	swap(n,m);
	REP (i,n)
	{
		REP(j, m)
		{
			nextInt(g[i][j]);
			if (g[i][j] == 2)
			{
				xbegin = i;
				ybegin = j;
			}
			if (g[i][j] == 3)
			{
				xend = i;
				yend = j;
			}
		}
	}
}


int ans = 0;
const int dx[]={0,0,-1,1};
const int dy[]={1,-1,0,0};

void dfs(int nx, int ny, int dir,int bu)
{

	if (bu > 10)	return;
	if (nx < 0 || ny <0 || nx >= n || ny >=m)	return;//出界,不合法
	//cout<<nx<<" "<<ny<<" "<<dir<<" "<<bu<<endl;

	if (nx == xend && ny == yend)
	{
		ans = min(ans, bu);
	}

	int i;

	if (dir != -1)
	{
		int wx = nx + dx[dir];
		int wy = ny + dy[dir];
		if (g[wx][wy] == 0)
		{
			dfs(wx,wy,dir,bu);
		}
		else
		{
			g[wx][wy] = 0;
			dfs(nx,ny,-1,bu);
			g[wx][wy] = 1;
		}
		return;
	}

	REP(i,4)
	{
		int wx = nx + dx[i];
		int wy = ny + dy[i];
		if (g[wx][wy]==1)	continue;
		dfs(wx,wy, i, bu + 1);
	}
}


void doit()
{
	ans = 0x7fffffff;
	//cout << xbegin<<" "<<ybegin<<" "<<xend<<" "<<yend<<endl;
	g[xbegin][ybegin] = g[xend][yend] = 0;
	dfs(xbegin,ybegin,-1,0);
	if (ans == 0x7fffffff)	ans = -1;
	printf("%d\n", ans);
}

int main()
{

	while (~scanf("%d %d",&n, &m))
	{
		double begin = clock();
		if (!n && !m)	break;
		init();
		doit();
		//cout << (clock()-begin)/1000 << endl;
	}


}

/*
6 6 
1 0 0 2 1 0 
1 1 0 0 0 0 
0 0 0 0 0 3 
0 0 0 0 0 0 
1 0 0 0 0 1 
0 1 1 1 1 1


*/


你可能感兴趣的:(挑战第二章 poj 3009 水题DFS)