牛客 - 车辆调度(dfs)
生活随笔
收集整理的這篇文章主要介紹了
牛客 - 车辆调度(dfs)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個 n * m 的矩陣,其中 ' R ' 表示遙控車,' D ' 表示目的地,' X ' 表示障礙物,每一秒都可以操控任意一個遙控車向四個方向中的任意方向移動,不過移動必須滿足直到撞到空地的邊界、障礙物或其他遙控車后才能停止,很像小時候玩過的推冰塊游戲。然后問,能否存在一種方法,使得在第 k 分鐘時使得任意一個遙控車到達任意一個目的地
題目分析:因為所有數據都很小,我們不妨計算一下dfs爆搜的時間復雜度,至多有 4 個遙控車,每個遙控車有 4 個方向,也就是說每一秒鐘有 4 * 4 = 16 種情況,時間 k 至多只有 5 秒,也就是說時間復雜度為 16^5 ,1e6 左右,這樣直接模擬就好了
這個題目主要是為了紀念一下第一次自己動手寫dfs,并且 1A 的題目吧
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> using namespace std;typedef long long LL;typedef unsigned long long ull;const LL inf=0x3f3f3f3f;const int N=15;const int b[4][2]={0,1,0,-1,1,0,-1,0};int n,m,k;char maze[N][N];bool vis[N][N];vector<pair<int,int>>pos;bool check() {for(int i=0;i<pos.size();i++)if(vis[pos[i].first][pos[i].second])return true;return false; }bool check_bound(int x,int y) {return x>0&&y>0&&x<=n&&y<=m; }bool dfs(int step) {if(step==0) return check();for(int i=0;i<pos.size();i++)//枚舉車輛 for(int k=0;k<4;k++)//枚舉方向 {int sx=pos[i].first,sy=pos[i].second;maze[sx][sy]='.';int x=sx,y=sy;int xx=x+b[k][0];int yy=y+b[k][1];while(check_bound(xx,yy)&&maze[xx][yy]!='R'&&maze[xx][yy]!='X'){x=xx,y=yy;xx+=b[k][0];yy+=b[k][1];}maze[x][y]='R';pos[i].first=x,pos[i].second=y;if(dfs(step-1))return true;pos[i].first=sx,pos[i].second=sy;maze[x][y]='.';maze[sx][sy]='R';}return false; }int main() { #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif // ios::sync_with_stdio(false);scanf("%d%d%d",&m,&n,&k);for(int i=1;i<=n;i++)scanf("%s",maze[i]+1);for(int i=1;i<=n;i++)for(int j=1;j<=m;j++){if(maze[i][j]=='D')vis[i][j]=true;if(maze[i][j]=='R')pos.push_back(make_pair(i,j));}if(dfs(k))puts("YES");elseputs("NO");return 0; }?
總結
以上是生活随笔為你收集整理的牛客 - 车辆调度(dfs)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛客 - 斐波那契和(杜教BM)
- 下一篇: 牛客 - 弦(卡特兰数)