sicily 1889解題報告(bfs維護兩個隊列,實現最短路徑)

題目:

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
For each test data set, one output data set should be generated as follow:
Generates one line containing one integer which indicates the minimum cost Max need to take for the game.

題目意思:一個網格里面有可能有兩種字符“#”和“@”,如果跨越相同字符的網格不用花費,跨越不同的網格需要消耗一個單元,可以朝上下左右四個方向走,現給定初始位置和目標位置,要求求出最小的花費值,例如:

5 5
#@#@#
@#@#@
#@#@#
@#@#@
#@#@#
0 0 4 4

則最少8個單元的耗費值

解題思路:

這題是一個典型的最短路算法

方法1:把網格看成n×m個點,每個點有四條邊,距離已知,求出起始點和目標點的最短距離

           點共n*m=250000個,比較多,可以採用堆+dijkstra的方法,複雜度爲(n*m*(log(n*m)+4)),勉強能過

      2:此題開始想到用SPFA的方法,結果超時

 

比較好的解法:維護兩個隊列,進行bfs,第一個隊列存放“#”的點,第二個隊列存放“@”的點

                     從起始位置出發廣搜,遇到和自己相同符號的壓入自己所在的隊列,否則壓入另一個隊列,直到隊列爲空,對另一個隊列進行廣搜,這樣來回交替,直到兩個隊列都爲空,求出結果。

代碼如下:

   
 
     
 
 
   

       
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章