Topic links: http://oj.ecustacm.cn/problem.php?id=1284
Title Description
The following grid 10, enter the number 0-9. Requirements: not adjacent two consecutive numbers.
(Left and right, up and down, diagonally are considered adjacent) a number of possible solutions to fill the number of total?
(Left and right, up and down, diagonally are considered adjacent) a number of possible solutions to fill the number of total?
Export
Please fill represents an integer number of programs.
Ideas:
Adopt methods to traverse each square of DFS, we all met each square to determine what its left and right, up and down, diagonal whether the meaning of the questions, then was put in line.
And then for us to take a two gaps is one entrance exit way to traverse just fine
#include <iostream> #include <algorithm> #include <string> #include <string.h> #include <vector> #include <map> #include <stack> #include <set> #include <queue> #include <math.h> #include <cstdio> #include <iomanip> #include <time.h> #define LL long long #define INF 0x3f3f3f3f #define ls nod<<1 #define rs (nod<<1)+1 const intmaxn 1E5 + = 10 ; const LL mod = 20010905 ; const int r = 3 , c = 4 ; int map [ 10 ] [ 10 ] twice [ 20 ] cnt; int say [ 8 ] [ 2 ] = { 0 - 1 - 1 - 1 - 1 , 0 , - 1 , 1 , 0 , 1 , 1 , 1 , 1 , 0,1,-1}; bool check(int x,int y,int n) { for (int i = 0;i < 8;i++) { int nx = x + dir[i][0]; int ny = y + dir[i][1]; if (nx >= 0 && nx < r && ny >= 0 && ny < c) { if (map[nx][ny] == n-1 || map[nx][ny] == n+1) return false; } } return true; } void dfs(int dep,int pos) { if (dep == 2 && pos == 3) { cnt++; return ; } if (pos >= c) dfs(dep+1,0); else { for (int i = 0;i <= 9;i++) { if (!vis[i] && check(dep,pos,i)) { vis[i] = 1; map[dep][pos] = i; dfs(dep,pos+1); map[dep][pos] = -10; vis[i] = 0; } } } } int main() { for (int i = 0;i < 10;i++) { for (int j = 0;j < 10;j++) map[i][j] = -10; } memset(vis,0, sizeof(vis)); cnt = 0; dfs(0,1); printf("%d\n",cnt); return 0; }
Of course, there must be violence cup method violence:
#include<bits/stdc++.h> using namespace std; int main() { int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int ans = 0; do { if((abs(a[0]-a[1])!=1)&&(abs(a[1]-a[2])!=1)&&(abs(a[3]-a[4])!=1)&&(abs(a[4]-a[5])!=1)&& (abs(a[5]-a[6])!=1)&&(abs(a[7]-a[8])!=1)&&(abs(a[8]-a[9])!=1)&& (abs(a[0]-a[4])!=1)&&(abs(a[1]-a[5])!=1)&&(abs(a[2]-a[6])!=1)&& (abs(a[3]-a[7])!=1)&&(abs(a[4]-a[8])!=1)&&(abs(a[5]-a[9])!=1)&& (abs(a[0]-a[3])!=1)&&(abs(a[0]-a[5])!=1)&&(abs(a[1]-a[4])!=1)&& (abs(a[1]-a[6])!=1)&&(abs(a[2]-a[5])!=1)&&(abs(a[4]-a[7])!=1)&&(abs(a[4]-a[9])!=1)&& (abs(a[3]-a[8])!=1)&&(abs(a[5]-a[8])!=1)&&(abs(a[6]-a[9])!=1)) ans++; }while(next_permutation(a,a+10)); cout<<ans<<endl; }