Tempter of the Bone

代码运行时间,不能小于1000ms,很奇怪,

1.将字符数组改成整形数组,无效

2.将work()的参数由一维整形数组换成整形变量,无效

3.将动态申请空间改为静态申请,无效

///////////////////////////////////////////////////////

最后加了一个return,解决了

我觉得应该是加了return后就少做一次if判断

///编程要严谨啊

#include<iostream>
using namespace std;

void work(char **map, int T, int S0, int S1, int &S2, int D0, int D1, int N, int M)
{
	if (S0 == D0 && S1 == D1)					//判断到出口
	{
		if (T == 0)								//判断到出口时走了几步
			S2 = 1;
		return;										//*****************这个return节省了时间**************
	}
	if (S2 == 0 && T > 0)						//没有走出,并且还有步数剩余才递归
	{
		map[S0][S1] = 'E';
		if (S0 + 1 < N&&map[S0 + 1][S1] != 'X'&&map[S0 + 1][S1] != 'E')	//down
		{
			work(map, T - 1, S0 + 1, S1, S2, D0, D1, N, M);
		}
		if (S1 + 1 < M&&map[S0][S1 + 1] != 'X'&&map[S0][S1 + 1] != 'E')		//right
		{
			work(map, T - 1, S0, S1 + 1, S2, D0, D1, N, M);
		}
		if (S0 - 1 >= 0 && map[S0 - 1][S1] != 'X'&&map[S0 - 1][S1] != 'E')	//up
		{
			work(map, T - 1, S0 - 1, S1, S2, D0, D1, N, M);
		}
		if (S1 - 1 >= 0 && map[S0][S1 - 1] != 'X'&&map[S0][S1 - 1] != 'E')  //left
		{
			work(map, T - 1, S0, S1 - 1, S2, D0, D1, N, M);
		}
		map[S0][S1] = '.';
	}
	else
		return;
}

int main()
{
	int N, M, T, S0, S1, S2, D0, D1;
	char **map;
	cin >> N >> M >> T;
	while (N != 0 && M != 0 && T != 0)
	{
		map = new char*[N];
		for (int i = 0; i < N; i++)
		{
			map[i] = new char[M];                   //动态数组初始化
			for (int j = 0; j < M; j++)
			{
				cin >> map[i][j];
				if (map[i][j] == 'S')
				{
					S0 = i; S1 = j; S2 = 0;
				}
				if (map[i][j] == 'D')
				{
					D0 = i; D1 = j;
				}
			}
		}
		work(map, T, S0, S1, S2, D0, D1, N, M);
		if (S2 == 1)
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
		cin >> N >> M >> T;
	}
	return 0;
}


posted @ 2015-07-19 22:36  A_yes  阅读(138)  评论(0编辑  收藏  举报