杭电OJ 1010(C++)

本题是基本的路径搜索题目,使用深度优先搜索(DFS)和奇偶剪枝。

#include 
#include 
#include 
using namespace std;

const int LEN = 10;
char map[LEN][LEN];
bool flag;
int N, M, T;
int sx, sy, ex, ey;
int n[4][2] = { 0, 1, 1, 0, 0, -1, -1, 0 }; //下一步走法
void DFS(int x, int y, int time);

int main()
{
	while (cin >> N >> M >> T)
	{
		if (N == 0 && M == 0 && T == 0)
			break;

		flag = false; //每次测试新数据前要更新flag,否则flag = true不会改变
		int wallNum = 0;
		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < M; j++)
			{
				cin >> map[i][j];
				switch (map[i][j])
				{
				case 'S':
					sx = i;
					sy = j;
					break;
				case 'D':
					ex = i;
					ey = j;
					break;
				case 'X':
					++wallNum;
					break;
				}
			}
		}

		if (N*M - wallNum <= T)
		{
			cout << "NO" << endl;
			continue;
		}
		map[sx][sy] = 'X'; //起始点走过之后要更新为'X'
		DFS(sx, sy, 0);
		if (flag)
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}
	return 0;
}

void DFS(int x, int y, int time)
{
	if (x < 0 || x >= N || y < 0 || y >= M) //越界
		return;
	if (x == ex && y == ey && time == T) //到达终点
	{
		flag = true;
		return;
	}

	int temp = T - time - abs(x - ex) - abs(y - ey); //奇偶剪枝
	if (temp < 0 || temp % 2 == 1)
		return;

	for (int i = 0; i < 4; i++) //深度优先搜索
	{
		int nx = x + n[i][0];
		int ny = y + n[i][1];
		if (map[nx][ny] != 'X')
		{
			map[nx][ny] = 'X';
			DFS(nx, ny, time + 1);
			map[nx][ny] = '.'; //回退时还原走过的块
			if (flag)
				return;
		}
	}
}

 

你可能感兴趣的:(杭电OJ)