最长路径——百度2017校招机试题

解析:这道题目刚拿到手,很容易就确定是道优先搜索算法的题目,和我博客之前写的一道迷宫题目一致。根据题目,我们只要在输入的矩阵中找到最高点和最低点,然后从最高的地方开始4个方向的轮训,直到最后到达最低点。那既然是要求最长的奔跑路径,那么每次4个方向轮训肯定是要走当中值最大的那一个了。

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

typedef struct _Point  
{  
	int x;  
	int y;  
	_Point()  
	{  
		x = 0;  
		y = 0;  
	};  
	_Point(const int& v_nx, const int& v_ny)  
	{  
		x = v_nx;  
		y = v_ny;  
	};  
	bool operator==(const _Point& v_p)  
	{  
		if(x == v_p.x && y == v_p.y)  
		{  
			return true;  
		}  
		return false;  
	}  
}POINT, *PPOINT;  

int main()
{
	int X, Y = 0;
	int MyMap[100][100] = {0};
	int dir[4][2] = {{0, 1},{1, 0},{0, -1},{-1, 0}};
	int xMax, yMax = 0;
	int xMin, yMin = 0;
	int nMax = MyMap[0][0];
	int nMin = -1;
	while(cin >> X >> Y)
	{
		for(int i = 0; i < X; ++i)
		{
			for(int j = 0; j < Y; ++j)
			{
				cin >> MyMap[i][j];
				if(MyMap[i][j] > nMax)				//!<记录最高的位置
				{
					nMax = MyMap[i][j];
					xMax = i;
					yMax = j;
				}
				
				if(MyMap[i][j] < nMin || nMin == -1) //!<记录最低的位置
				{
					nMin = MyMap[i][j];
					xMin = i;
					yMin = j;
				}
			}
		}

		int MyVisit[100][100] = {0};
		int nLength = 0;
		bool bEnd = false;
		POINT pointStart;
		pointStart.x = xMax;
		pointStart.y = yMax;

		POINT pointEnd;
		pointEnd.x = xMin;
		pointEnd.y = yMin;

		stack<POINT> Queue;
		Queue.push(pointStart);
		MyVisit[pointStart.x][pointStart.y] = 1;
		nLength++;
		while(!Queue.empty())
		{
			POINT pointCur = Queue.top();
			if(pointCur == pointEnd)
			{
				break;
			}
		
			POINT pointNext;
			int nGaoDu = 0;
			for(int i = 0; i < 4; ++i)
			{
				POINT pointTemp(pointCur.x + dir[i][0], pointCur.y + dir[i][1]);
				if(pointTemp.x >= 0 && pointTemp.y >= 0 &&  //!<判断是否越界
					pointTemp.x < X && pointTemp.y < Y)  
				{  
					if(MyVisit[pointTemp.x][pointTemp.y] == 0)//判断节点是否访问过  
					{  
						if(MyMap[pointTemp.x][pointTemp.y] > nGaoDu)
						{
							pointNext.x = pointTemp.x;
							pointNext.y = pointTemp.y;
							nGaoDu = MyMap[pointTemp.x][pointTemp.y];
						} 
					}  
				} 
			}
			Queue.pop();
			Queue.push(pointNext);
			MyVisit[pointNext.x][pointNext.y] = 1;
			nLength++;

		}

		cout << nLength << endl;

	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/fzuim/article/details/78143134