| ||
| ||
| ||
题目:
Problem
Max is lately playing a game. Given a n*m board, there are only two types of grid on it: # and @. And the rule is simple: Given a start position to Max, and Max can move to four direction for each step, up, down, left, right. When moving between two same type grids, it costs zero, otherwise, it costs one. Now, Max gets two different positions on the board: the start position and the target position, he wants to know how many costs he need to spend to achieve the game at least.
Input
Input contains multiple test data sets. For each data set, first comes two integers in one line: n, m (1 < = n, m <= 500), stands for the number of row and the number of column of the board. Then comes n lines with m grid characters per each. The characters are only @ or #. Then four integers in one line follow: x1, y1, x2, y2 ( 0<= x1, x2 < n, 0<= y1, y2 < m) which is the start position and the end position correspondingly. Input is terminated by EOF. | ||
Output 题目意思:一个网格里面有可能有两种字符“#”和“@”,如果跨越相同字符的网格不用花费,跨越不同的网格需要消耗一个单元,可以朝上下左右四个方向走,现给定初始位置和目标位置,要求求出最小的花费值,例如: 5 5 则最少8个单元的耗费值 解题思路: 这题是一个典型的最短路算法 方法1:把网格看成n×m个点,每个点有四条边,距离已知,求出起始点和目标点的最短距离 点共n*m=250000个,比较多,可以采用堆+dijkstra的方法,复杂度为(n*m*(log(n*m)+4)),勉强能过 2:此题开始想到用SPFA的方法,结果超时
比较好的解法:维护两个队列,进行bfs,第一个队列存放“#”的点,第二个队列存放“@”的点 从起始位置出发广搜,遇到和自己相同符号的压入自己所在的队列,否则压入另一个队列,直到队列为空,对另一个队列进行广搜,这样来回交替,直到两个队列都为空,求出结果。 代码如下:
|