BFS模板【洛谷P1162】
阿新 • • 發佈:2018-11-10
奉上題目連結啦:https://www.luogu.org/problemnew/show/P1162
一開始是懵的,這咋搜啊,在圈裡咋限定方向啊,這咋做啊!!????
在隊友@TDD的啟發下,原來我們反其道而行之,題目要求在圈裡填數字,我們從四條邊向圖裡面搜,把圈外的都填上-1,最後把0當成2輸出,就OK啦!!!
咦?怎麼輸出出來還是和原來的一樣,怎麼沒有2啊?????
哦哦哦,起點又忘標記了
程式碼程式碼:
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> P; const int maxn = 35; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; int G[maxn][maxn]; int n; void init() { memset(G,0,sizeof(G)); } void bfs(int x,int y) { queue<pair<int,int> > q; q.push(P(x,y)); while(!q.empty()) { int nx = q.front().first; int ny = q.front().second; q.pop(); for(int i=0;i<4;i++) { int nowx = nx+dx[i]; int nowy = ny+dy[i]; if(nowx>=1 && nowx<=n && nowy>=1 && nowy<=n) { if(!G[nowx][nowy]) { G[nowx][nowy] = -1; q.push(P(nowx,nowy)); } } } } } int main() { while(cin>>n) { init(); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { cin>>G[i][j]; } } for(int i=1;i<=n;i++) { if(G[i][1]==0) { G[i][1] = -1; bfs(i,1); } } for(int i=1;i<=n;i++) { if(G[1][i]==0) { G[1][i] = -1; bfs(1,i); } } for(int i=1;i<=n;i++) { if(G[i][n]==0) { G[i][n] = -1; bfs(i,n); } } for(int i=1;i<=n;i++) { if(G[n][i]==0) { G[n][i] = -1; bfs(n,i); } } for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(G[i][j]==0) { cout<<"2"; } else if(G[i][j]==-1) { cout<<"0"; } else { cout<<G[i][j]; } if(j<n) { cout<<" "; } } cout<<endl; } } return 0; }
有時候思想被限定死了,這道題可能永遠做不出來。