單向DFS【洛谷P1101】
阿新 • • 發佈:2018-11-10
照例還是題目連結:https://www.luogu.org/problemnew/show/P1101
這題跟以往的DFS不同的是,它是單向的DFS(因為我做題少,所以第一次見到這種型別的題目)。
思路很簡單,但是對於第一次做這種單向DFS的我來說(我蒻),開始確實感覺無從下手。
這道題目和以往的DFS不同的地方在於,DFS的方向是在外面判斷的,然後還要記錄路徑,路徑記錄全了才能往vis裡面加true。
直接看程式碼吧,這道題應該只有我才會不做了。
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> P; const int maxn = 110; char G[maxn][maxn]; int vis[maxn][maxn]; int dx[]={0,1,-1,0,1,-1,1,-1}; int dy[]={1,0,0,-1,1,-1,-1,1}; map<char,char> mp; int n; struct node { int x; int y; }c[maxn]; void init() { memset(G,'0',sizeof(G)); memset(vis,0,sizeof(vis)); mp['y'] = 'i'; mp['i'] = 'z'; mp['z'] = 'h'; mp['h'] = 'o'; mp['o'] = 'n'; mp['n'] = 'g'; } void dfs(int x,int y,int k,int stp) { if(stp==7) { for(int i=0;i<7;i++) { vis[c[i].x][c[i].y] = 1; } return; } int nowx = x+dx[k]; int nowy = y+dy[k]; if(nowx>=1 && nowx<=n && nowy>=1 && nowy<=n) { if(stp==6 || G[nowx][nowy]==mp[G[x][y]]) { c[stp].x = nowx; c[stp].y = nowy; dfs(nowx,nowy,k,stp+1); } } } int main() { while(cin>>n) { init(); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { cin>>G[i][j]; if(G[i][j]=='y' || G[i][j]=='i' || G[i][j]=='z' || G[i][j]=='h' || G[i][j]=='o' || G[i][j]=='n' || G[i][j]=='g') { G[i][j] = G[i][j]; } else { G[i][j] = '*'; } } } for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(G[i][j]=='y') { for(int k=0;k<8;k++) { c[0].x = i; c[0].y = j; dfs(i,j,k,1); } } } } for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(vis[i][j]) { cout<<G[i][j]; } else { cout<<"*"; } } cout<<endl; } cout<<endl; } return 0; }
PS:今天寫了好幾篇題解,感覺今天做的題全部都是我無從下手的,今天真是收穫滿滿的一天。
PS:確實寫題解可以幫助理解程式碼。空想是不行的啊!