1. 程式人生 > >Codeforces Round #516 (Div. 2) D. Labyrinth ---- BFS+思維

Codeforces Round #516 (Div. 2) D. Labyrinth ---- BFS+思維

題目傳送門

做法:

  • 優先選取列,然後在向左右擴充套件。
  • 然鵝,有思路,卻不會處理,看了本場Rank1,有雙端佇列巧妙處理列和行的優先順序,才發現處理更簡潔+易懂。ORZ
  • 我們優先將列放到隊首,因為列是不需要消耗步數的,然後再將左右放到隊尾,然後依次訪問+標記,即可。

AC程式碼:

#include<bits/stdc++.h>
#define IO          ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define pb(x)       push_back(x)
#define sz(x)       (int)(x).size()
#define sc(x) scanf("%d",&x) #define pr(x) printf("%d\n",x) #define abs(x) ((x)<0 ? -(x) : x) #define all(x) x.begin(),x.end() #define mk(x,y) make_pair(x,y) #define debug printf("!!!!!!\n") #define fin freopen("in.txt","r",stdin) #define fout freopen("out.txt","w",stdout)
using namespace std; typedef long long ll; typedef pair<int,int> PII; const int mod = 1e9+7; const double PI = 4*atan(1.0); const int maxm = 1e8+5; const int maxn = 2e3+5; const int INF = 0x3f3f3f3f; const ll LINF = 1ll<<62; int n,m,sx,sy,nx,ny; char mmap[maxn][maxn]; bool vis[maxn][maxn]
; struct node { int x,y; int nx,ny; node(int x,int y,int nx,int ny){ this->x = x; this->y = y; this->nx = nx; this->ny = ny; } }; deque<node> q; int bfs() { int cnt = 0; while(!q.empty()) { node tmp = q.front(); q.pop_front(); int x = tmp.x,y = tmp.y; int nx = tmp.nx,ny = tmp.ny; if(vis[x][y]) continue; vis[x][y] = 1; cnt++; if(x-1>0 && mmap[x-1][y]!='*') q.push_front(node(x-1,y,nx,ny)); if(x+1<=n && mmap[x+1][y]!='*') q.push_front(node(x+1,y,nx,ny)); if(y-1>0 && mmap[x][y-1]!='*' && nx) q.push_back(node(x,y-1,nx-1,ny)); if(y+1<=m && mmap[x][y+1]!='*'&& ny) q.push_back(node(x,y+1,nx,ny-1)); } return cnt; } int main() { // fin; IO; cin>>n>>m>>sx>>sy>>nx>>ny; for(int i=1;i<=n;i++) cin>>mmap[i]+1; q.push_front(node(sx,sy,nx,ny)); cout<<bfs()<<endl; return 0; }