您的位置:首页 > 编程语言

华为编程大赛——公交站寻址

2017-08-21 15:47 106 查看


问题描述

一个N*N二维矩阵代表城市布局,元素值只有’.’,’X’
, ‘B’ , ‘S’,X代表当前位置,B代表路障,S代表公交站,’.’代表可行的路径。现给定路径长度Y,找到能够到达的公交站的个数,路径中不能包含路障。

路径长度定义:

1、 节点与其自身的距离为0

2、 节点与其上、下、左、右四个相邻节点距离都为1

l  要求实现函数

int FindStat (const char *Map, unsigned int iArrN, unsigned int iPathLen)
【输入】Map:     
城市布局
iArrN:         城市布局矩阵的行数
iPathLen:      给定的路径长度

【输出】无
【返回】能够到达的公交站个数
注:输入矩阵是以一维形式保存的二维数组,
比如输入为{‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’,’G’, ‘H’,
‘I’},
实际上表示如下3*3的矩阵
‘A’,’B’,’C’,
‘D’,’E’,’F’,
‘G’,’H’,’I’

l  示例

输入:"...S........X.S.....S....",
5, 3
返回:2 
输入:"S...S.........BS........X", 5, 5
返回:1
#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

#define CURRENT			0
#define UP				1
#define DOWN			2
#define LEFT			3
#define RIGHT			4

#define VIABLEPATH		'.'
#define ROADBLOCK		'B'
#define BUSSTATION		'S'
#define CURRLOCATION	'X'

// 			 up
//            |
//            |
// left---Location---right
//            |
//            |
//           down
void NextLocation(const char *Map, unsigned int iArrN, unsigned int iPathLen, unsigned int iLocation, list<unsigned int> *pStation, unsigned int direction)
{
if( Map == NULL || iArrN < 1 || iLocation > (iArrN * iArrN - 1) || pStation == NULL){
cout << "Function " << __func__ << " input error!" << endl;
return;
}

if(Map[iLocation] == BUSSTATION){
list<unsigned int>::iterator it = find(pStation->begin(), pStation->end(), iLocation);
if(it == pStation->end())
pStation->push_back(iLocation);
}
else if(Map[iLocation] == ROADBLOCK)
return;

if(iPathLen > 0){
//left
if((iLocation % iArrN != 0) && (direction != RIGHT)){
NextLocation(Map, iArrN, iPathLen - 1, iLocation - 1, pStation, LEFT);
}

//right
if(((iLocation + 1) % iArrN != 0) && (direction != LEFT)){
NextLocation(Map, iArrN, iPathLen - 1, iLocation + 1, pStation, RIGHT);
}

//up
if((iLocation >= iArrN) && (direction != DOWN)){
NextLocation(Map, iArrN, iPathLen - 1, iLocation - iArrN, pStation, UP);
}

//down
if((iLocation + iArrN < iArrN * iArrN) && (direction != UP)){
NextLocation(Map, iArrN, iPathLen - 1, iLocation + iArrN, pStation, DOWN);
}
}
}

int FindStat(const char *Map, unsigned int iArrN, unsigned int iPathLen)
{
unsigned int iLocation;
unsigned int i;
list<unsigned int> lStation;

for(i = 0; i < iArrN * iArrN; i++){
if(Map[i] == CURRLOCATION){
iLocation = i;
break;
}
}

if(i == iArrN * iArrN)
return 0;

NextLocation(Map, iArrN, iPathLen, iLocation, &lStation, CURRENT);

return lStation.size();
}

int main()
{
char Map[] = "...S........X.S.....S....";
unsigned int iArrN = 5;
unsigned int iPathLen = 3;

cout << FindStat(Map, iArrN, iPathLen) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: