In general, the basic dfs search starts directly from one point and then from this point to the next
But this problem uses another way of thinking dfs
Each point selection is not based on the previous point, but from the entire map to select points that have not been selected
That is to scan the map once and select the unused points from it. This method is often used in the case where the transfer rules between two points are complex. For example, in this problem, two points need to be used each time instead of one, and there are two directions at the same time.
When using this method, you need to pay attention to the need to return immediately after finding the first point.
#include <bits/stdc++.h> #include <hash_map> #include <hash_set> using namespace std; using namespace __gnu_cxx; //#pragma GCC optimize(2) #define n 3 #define m 10 int Map[3][10]; bool check(void) { for(int i = 0; i < n-1; i++) { for(int j = 0; j < m-1; j++) { int cc = Map[i][j]; if(Map[i+1][j] == cc && cc == Map[i][j+1] && cc == Map[i+1][j+1]) return false; } } return true; } set<string> ans; string tmp; void dfs(int count) { if(count == n*m) { tmp.clear(); char ch[3*10]; int t = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { ch[t++]= (Map[i][j]+'A'); } } tmp += ch; if(check() && ! ans.count(tmp)) { ans.insert(tmp); // cout << tmp << endl; } return; } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(Map[i][j] == 0) { if(j+1 < m && Map[i][j+1] == 0) { Map[i][j] = 1; Map[i][j+1] = 1; dfs(count + 2); Map[i][j] = 0; Map[i][j+1] = 0; } if(j+1 < m && Map[i][j+1] == 0) { Map[i][j] = 2; Map[i][j+1] = 2; dfs(count + 2); Map[i][j] = 0; Map[i][j+1] = 0; } if(i+1 < n && Map[i+1][j] == 0) { Map[i][j] = 1; Map[i+1][j] = 1; dfs(count+2); Map[i][j] = 0; Map[i+1][j] = 0; } if(i+1 < n && Map[i+1][j] == 0) { Map[i][j] = 2; Map[i+1][j] = 2; dfs(count+2); Map[i][j] = 0; Map[i+1][j] = 0; } return ; // Note, be sure to add, avoid double counting } } } } #define zpl int main(int argc, char *argv[]) { #ifdef zpl freopen("F:\\data.txt", "r", stdin); #endif // zpl dfs(0); cout << ans.size() << endl; return 0; }