1. 程式人生 > >程式設計題-華為-陸地最長跑道

程式設計題-華為-陸地最長跑道

晚上的程式設計題第三題,過了83%,剩餘case提示TLE,不知道怎麼優化(或者有什麼特殊情況沒考慮導致遞迴死迴圈?)。

思路:dfs+dp。 

 

#include<iostream>;
#include<vector>
using namespace std;

int m, n, h;

int max(int x, int y)
{
	return x > y ? x : y;
}

void findOcean(vector<vector<int>> a, vector<vector<bool>>& v, vector<vector<bool>>& o, int i, int j)
{
	if (v[i][j]==0)
	{
		v[i][j] = 1;
		if (a[i][j]<=0)
		{
			o[i][j] = 1;
			if (j + 1 < n && v[i][j + 1] == 0)
			{
				findOcean(a, v, o, i, j + 1);
			}
			if (j - 1 >= 0 && v[i][j - 1] == 0)
			{
				findOcean(a, v, o, i, j - 1);
			}
			if (i + 1 < m && v[i+1][j] == 0)
			{
				findOcean(a, v, o, i+1, j);
			}
			if (i - 1 >= 0 && v[i - 1][j] == 0)
			{
				findOcean(a, v, o, i-1, j);
			}
		}
	}
}

int findLongestTrack(vector<vector<int>> a, vector<vector<int>>& t, vector<vector<bool>>& o, int i, int j, int lastHeight)
{
	if (i<0||i>=m||j<0||j>=n||o[i][j]==1||lastHeight<=a[i][j])
	{
		return 0;
	}
	else if (t[i][j]!=0)
	{
		return t[i][j];
	}
	else
	{
		int left, right, up, down;
		left = findLongestTrack(a, t, o, i - 1, j, a[i][j]) +1 ;
		right = findLongestTrack(a, t, o, i + 1, j, a[i][j]) + 1;
		up = findLongestTrack(a, t, o, i, j+1, a[i][j]) + 1;
		down = findLongestTrack(a, t, o, i, j-1, a[i][j]) + 1;
		t[i][j] = max(left, max(right, max(up, down)));
		return t[i][j];
	}
}


int main()
{
	while (cin>>m>>n>>h)
	{
		vector<vector<int>> alt(m, vector<int>(n, 0));
		vector<vector<bool>> vis(m, vector<bool>(n, 0));
		vector<vector<bool>> ocean(m, vector<bool>(n, 0));
		int tmp;
		for (int i = 0; i < m; i++)
		{
			for (int j = 0; j < n; j++)
			{
				cin >> tmp;
				alt[i][j] = tmp - h;
				if (alt[i][j] <= 0 &&( i == 0 || i == m - 1 || j == 0 || j == n - 1))
				{
					ocean[i][j] = 1;
				}
			}
		}

		for (int i = 0; i < m; i++)
		{
			if (ocean[i][0])
			{
				findOcean(alt, vis, ocean, i, 0);
			}

			if (ocean[i][n-1])
			{
				findOcean(alt, vis, ocean, i, n-1);
			}
		}
		for (int j = 0; j < n; j++)
		{
			if (ocean[0][j])
			{
				findOcean(alt, vis, ocean, 0, j);
			}

			if (ocean[m-1][j])
			{
				findOcean(alt, vis, ocean, m-1, j);
			}
		}


		vector<vector<int>> track(m, vector<int>(n, 0));
		for (int i = 0; i < m; i++)
		{
			for (int j = 0; j < n; j++)
			{
				vis[i][j] = 0;
			}
		}

		for (int i = 0; i < m; i++)
		{
			for (int j = 0; j < n; j++)
			{
				if (ocean[i][j]==0)
				{
					track[i][j] = findLongestTrack(alt, track, ocean, i, j, 32768);
				}
			}
		}

		int ans = 0;
		for (int i = 0; i < m; i++)
		{
			for (int j = 0; j < n; j++)
			{
				if (track[i][j] > ans) { ans = track[i][j]; }
			}
		}
		cout << ans << endl;
	}
	return 0;
}