【題解】跳房子-C++


Description
奶牛按不太傳統的方式玩起小朋友玩的跳房子游戲,現給出一個5*%的由數字組成的網格。它們在格子中向前前跳,向后跳,向左跳,向右跳,跳到網格中另一個數字后,又這樣繼續跳(可能跳到某個已跳過的數字)。一共在網格中跳過五次后,它們經過的格子數組成一個六位數(可能是0開始頭的,例如000201).現問所有可以被跳出來的不同整數的總數。
Input
輸入共五行,每行五個數字.
Output
如題
Sample Input
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 2 1
1 1 1 1 1
Sample Output
15
HINT
111111, 111112, 111121, 111211, 111212, 112111, 112121, 121111, 121112,

121211, 121212, 211111, 211121, 212111, and 212121 can be constructed.

No other values are possible.

今天考試2題…
又是一道DFS,分別從每個點出發,往四周拓展,不打標記,深度超限就判斷當前情況是否出現過,沒出現過就標記然后cnt++,查找工作可以交給set來完成,這樣就不需要打標記這些了…
ov.

 1 /*
 2 這道題看題目描述感覺ans用int存,前導0存不下,所以干脆就用字符串一位一位加
 3 */ 
 4 #include<bits/stdc++.h>
 5 using namespace std;
 6 int cnt;
 7 string ans;
 8 char mp[11][11];
 9 int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
10 bool in(int x,int y)
11 {
12     return 1<=x&&x<=5&&1<=y&&y<=5;
13 }
14 set<string> s;
15 void dfs(int x,int y,int dep,string an)
16 {
17     an+=mp[x][y];
18     if(dep==6)
19     {
20         if(!s.count(an))
21         {
22             s.insert(an);
23             cnt++;
24         }
25         return;
26     }
27     for(int i=0;i<4;i++)
28     {
29         int nx=x+dir[i][0],ny=y+dir[i][1];
30         if(in(nx,ny))
31         {
32             dfs(nx,ny,dep+1,an);
33         }
34     }
35     return;
36 }
37 int main()
38 {
39     for(int i=1;i<=5;i++)
40         for(int j=1;j<=5;j++)
41             cin>>mp[i][j];
42     for(int i=1;i<=5;i++)
43     {
44         for(int j=1;j<=5;j++)
45         {
46             dfs(i,j,1,"");
47         }
48     }
49     cout<<cnt<<endl;
50     return 0;
51 }

 


免責聲明!

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



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