<pre name="code" class="cpp">#include <stdio.h>
#define DEBUG 1
#define TESTCASES 9
int map[300][100];
typedef struct Node{
int row;
int column;
int steps;
}Node;
Node queue[20000];
int head, tail;
Node NodePushed, NodePoped;
int directionArray[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1};
int main(){
#if DEBUG
int testCase;
for (testCase = 1; testCase <= TESTCASES; testCase++){
char inputFileName[20] = "inputx.txt";
inputFileName[5] = '1' + (testCase - 1);
freopen(inputFileName, "r", stdin);
printf("\n#%d\n", testCase);
#endif
int height, width;
char cha;
scanf("%d%d", &width, &height);
//注意字符的输入处理,过滤掉换行符
scanf("%c", &cha);
int heightLines = (height << 1) + 1;
int widthLines = (width << 1) + 1;
head = tail = 0;
int row, column;
for (row = 0; row < heightLines; row++){
for (column = 0; column < widthLines; column++){
scanf("%c", &cha);
if (cha == '+' || cha == '-' || cha == '|')
map[row][column] = 0;
else if (row == 0 || row == heightLines - 1 || column == 0 || column == widthLines - 1){
//从出口处开始逆向BFS会使得问题变得简单很多
NodePushed.row = row;
NodePushed.column = column;
//出口处的步数初始化为1,没有藩篱的位置都当作可以行走,最终的步数除以2便可以
NodePushed.steps = 1;
queue[tail++] = NodePushed;
} else
map[row][column] = 1;
}
scanf("%c", &cha);
}
while (head < tail){
NodePoped = queue[head++];
int directionIndex;
for (directionIndex = 0; directionIndex < 4; directionIndex++){
row = NodePoped.row + directionArray[directionIndex][0];
column = NodePoped.column + directionArray[directionIndex][1];
if (row >= 0 && row < heightLines && column >= 0 && column < widthLines && map[row][column] == 1){
map[row][column] = 0;
NodePushed.row = row;
NodePushed.column = column;
NodePushed.steps = NodePoped.steps + 1;
queue[tail++] = NodePushed;
}
}
}
printf("%d\n", queue[tail - 1].steps >> 1);
#if DEBUG
}
#endif
return 0;
}
USACO 2.4 Overfencing (BFS)
最新推荐文章于 2021-12-15 19:28:34 发布