1 solutions
-
0
C :
#include <stdio.h> #include <malloc.h> #define true 1 #define false 0 int *result; int num; int *flag; void dfs(int i); int count; int main(void){ int i; scanf("%d",&num); count=0; result=(int *)malloc(sizeof(int)*num); flag=(int *)malloc(sizeof(int )*num); for(i=0;i<num;i++){ flag[i]=false; } dfs(0); printf("Total=%d\n",count); return 0; } void dfs(int i){ int j; if(i+1>num){ for(j=0;j<num;j++){ printf("%d ",result[j]); } printf("\n"); count++; }else{ for(j=0;j<num;j++){ if(flag[j]==false){ result[i]=j+1; flag[j]=true; dfs(i+1); flag[j]=false; } } } }
C++ :
#include<iostream> #include<cstring> #include<cstdio> using namespace std; int n,a[51],b[51],ans=0; bool f; void find(int m) { if(m==n+1) { f=true; memset(b,0,sizeof(b)); for(int i=1;i<=n;i++) if(b[a[i]]==1){f=false;break;} else b[a[i]]=1; if(f) { for(int i=1;i<=n-1;i++) cout<<a[i]<<" "; cout<<a[n]<<endl;ans++; } return; } for(int i=1;i<=n;i++) { a[m]=i; find(m+1); } } int main() { cin>>n; find(1); cout<<"Total="<<ans<<endl; return 0; }
Java :
import java.util.*; public class Main{ public static int [] arr; public static boolean [] book; public static int [] print; public static int n,count; public static void main(String[] args) { Scanner cin = new Scanner(System.in); n = cin.nextInt(); init(); dfs(1); System.out.println("Total="+count); } /* Depth First Search */ public static void dfs(int index){ if(index == n+1){ count += 1; for(int i = 1; i < index; i ++){ if(i == index-1){ System.out.println(print[i]); }else{ System.out.print(print[i]+" "); } } return ; } for(int i=1; i <= n; i ++){ if(book[i] ==false){ book[i] = true; print[index] = arr[i]; dfs(index+1); book[i] = false; } } } /* Initialize Variable */ public static void init(){ book = new boolean[n+1]; for(int i = 1; i <= n; i ++){ // initialize the book array book[i] = false; } arr = new int[n+1]; for(int i = 1; i <= n; i ++){ // initialize the arr array arr[i] = i; } print = new int[n+1]; } }
- 1
Information
- ID
- 688
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- (None)
- Tags
- # Submissions
- 0
- Accepted
- 0
- Uploaded By