HDUOJ 1428
阿新 • • 發佈:2018-11-27
漫步校園
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5161 Accepted Submission(s): 1610
Output 針對每組測試資料,輸出總的路線數(小於2^63)。
Sample Input 3 1 2 3 1 2 3 1 2 3 3 1 1 1 1 1 1 1 1 1
Sample Output 1 6 BFS
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4#include <algorithm> 5 #include <cmath> 6 #include <queue> 7 8 using namespace std; 9 10 const int INF = 0x3f3f3f3f;//無窮大 11 const int maxn = 51; 12 13 int go[4][2] = { 1,0,-1,0,0,1,0,-1 };//方向 14 struct node 15 { 16 int x, y; 17 }; 18 19 int board[maxn][maxn];//記錄位置(i,j)的值 20 int dis[maxn][maxn];//位置(i,j)所經歷的最短路 21 int vis[maxn][maxn], n;//記錄是否走過 22 23 bool operator < (const node &t1, const node &t2) 24 { 25 return dis[t1.x][t1.y] > dis[t2.x][t2.y]; 26 }//過載了比較運算子,用於 27 28 long long num[maxn][maxn];//注意資料範圍 29 30 void bfs() 31 { 32 int i; 33 priority_queue<node> q;//定義一個優先佇列 34 node now, next;//動態儲存現在所在位置和下一步的位置對應的值 35 36 now.x = n; 37 now.y = n;//重點,從重點開始搜尋 38 39 q.push(now); 40 memset(vis, 0, sizeof(vis));//根據求最小的決策,初始化為0 41 vis[n][n] = 1;//搜尋開始 42 while (!q.empty())//搜尋持續到佇列為空 43 { 44 now = q.top(); 45 q.pop(); 46 for (i = 0; i <= 3; i++) 47 { 48 next.x = now.x + go[i][0]; 49 next.y = now.y + go[i][1]; 50 if (next.x >= 1 && next.x <= n && next.y >= 1 && next.y <= n && dis[next.x][next.y] > dis[now.x][now.y]) 51 //加上計數陣列累加的條件 52 { 53 num[next.x][next.y] += num[now.x][now.y];//記錄最短路的數量 54 if (!vis[next.x][next.y] && dis[next.x][next.y] >= dis[now.x][now.y] + board[next.x][next.y]) 55 { 56 dis[next.x][next.y] = dis[now.x][now.y] + board[next.x][next.y]; 57 vis[next.x][next.y] = 1;//將next標記為已訪問 58 q.push(next);//更新佇列 59 } 60 } 61 } 62 } 63 } 64 65 int main() 66 { 67 int i, j; 68 while (~scanf_s("%d", &n)) 69 { 70 memset(dis, 0x3f3f, sizeof(dis)); 71 memset(num, 0, sizeof(num)); 72 num[n][n] = 1; 73 74 for (i = 1; i <= n; i++) 75 for (j = 1; j <= n; j++) 76 scanf_s("%d", &board[i][j]); 77 78 dis[n][n] = board[n][n]; 79 80 bfs(); 81 82 printf("%I64d\n", num[1][1]);//long long 型別對應的格式字元 83 } 84 return 0; 85 }