bfs(最短路徑)


https://ac.nowcoder.com/acm/contest/993/F


題意:從(0,0)到X , Y最少要走幾步,其中有一些點是泥坑不能走。

思路:bfs注意:該題坐標會出現負數,所以標記數組要統一加500轉化為正數。或則直接用map標記。

#include <iostream> #include <iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include <stdio.h> #include <string.h> #include <stack> #include <vector> #include <queue> #include <set>
using namespace std; const int N = 500 ; int   x[10009] , y[10009] , vis[1009][1009]; int len1 , len2 , dir[4][2] = {{1 , 0} , {-1 , 0}, {0 , 1} ,{0 , -1}}; int mx , my , p; struct Node{ int x, y , ans ; Node(int x = 0, int y = 0 , int ans = 0){ this->x = x ; this->y = y ; this->ans = ans ;//記錄步數 } }n[10009]; bool check(int x , int y) { if(!vis[x + N][y + N] && x + 500 <= 1000 && x + 500 >= 0 && y + 500 <= 1000 && y + 500 >= 0) return true ; else
        return false ; } int bfs(int x , int y) { queue<Node>q; q.push(Node(x , y , 0)); vis[x + N][y + N] = 1 ; Node temp , step ; while(!q.empty()) { temp = q.front(); q.pop() ; if(temp.x == mx && temp.y == my) { return temp.ans ; } for(int i = 0 ; i < 4 ; i++) { step.x = temp.x + dir[i][0]; step.y = temp.y + dir[i][1]; step.ans = temp.ans + 1 ; if(check(step.x , step.y)) { vis[step.x + N][step.y + N] = 1 ; q.push(Node(step)); } } } } void init() { memset(vis , 0 , sizeof(vis)); } int main() { while(~scanf("%d%d%d" , &mx , &my , &p)) { init() ; for(int i = 0 ; i < p ; i++) { scanf("%d%d" , &n[i].x , &n[i].y); vis[n[i].x + N][n[i].y + N] = 1 ; } cout << bfs(0 , 0) <<endl ; } return 0; }

 

#include <iostream> #include <iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include <stdio.h> #include <string.h> #include <stack> #include <vector> #include <queue> #include <set>
using namespace std; const int N = 500 ; int   x[10009] , y[10009] , vis[1009][1009]; int len1 , len2 , dir[4][2] = {{1 , 0} , {-1 , 0}, {0 , 1} ,{0 , -1}}; int mx , my , p; struct Node{ int x , y , step ; }; void bfs() { queue<Node>q; q.push({500 , 500 , 0}); vis[500][500] = 1 ; while(!q.empty()) { Node temp = q.front(); q.pop() ; int x = temp.x , y = temp.y , s = temp.step ; if(x == mx + 500 && y == my + 500) { printf("%d\n" , s); break ; } for(int i = 0 ; i < 4 ; i++) { int tx = x + dir[i][0]; int ty = y + dir[i][1]; int ts = s + 1 ; if(tx < 0 || tx > 1000 || ty < 0 || ty > 1000) { continue ; } if(vis[tx][ty]) continue ; q.push({tx , ty , ts}); vis[tx][ty] = 1 ; } } } void init() { memset(vis , 0 , sizeof(vis)); } int main() { while(~scanf("%d%d%d" , &mx , &my , &p)) { init() ; for(int i = 0 ; i < p ; i++) { int a , b ; scanf("%d%d" , &a , &b); vis[a + N][b + N] = 1 ; } bfs(); } return 0; }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM