八皇后和N皇后以及ios實現(xiàn)界面動態(tài)尋找解

一、用枚舉法實現(xiàn)
思路:枚舉所有的可能來,可以看成一個樹形結(jié)構(gòu),到了葉子節(jié)點再去判斷是不是可行解

二、用回溯法實現(xiàn)
思路:在枚舉法的基礎(chǔ)上先進行判斷是不是可以放的點,再去進行遞歸

三、實現(xiàn)用了2種方法,一個是一維數(shù)組,一個是二維數(shù)組。一維數(shù)組中數(shù)組下標(biāo)為皇后坐標(biāo)的行,數(shù)組中對應(yīng)的值為皇后坐標(biāo)的列

四、以下是代碼部分,并且實現(xiàn)了動態(tài)尋找解(ios界面)
代碼在最下面,可供參考

#include"iostream"
using namespace std;
int cnt=0;
int n;

//*********************蠻力法
int judge(int a[])
{
    for(int i=0;i<n;i++)
    {
        for(int j=i+1;j<n;j++)
        {
            if(abs(a[j] - a[i]) == abs(j-i)||a[j] == a[i])
                return false;
        }
    }
    return true;
}


void queen(int a[],int temp)
{
    if(temp==n)
    {
        if(judge(a))
        {
            cnt++;
             //cout<<"為八皇后的解"<<endl;
        }
    }
    else
    {
        for(int i=0;i<n;i++)
        {
            a[temp]=i;
            queen(a, temp+1);
        }
    }
}
//**********************************
//回溯法
bool CanPlace(int row,int col,int **chess)
{
    for(int i=0;i<n;i++){
        if(chess[i][col]==1){//check col
            return false;
        }
        if(chess[row][i]==1){//check row
            return false;
        }
    }
    
    
    for(int i=0;i<n;i++){//check left-front
        if(row-i<0||col-i<0){
            break;
        }
        if(chess[row-i][col-i]==1){
            return false;
        }
    }
    
    
    for(int i=0;i<n;i++){//check right-front
        if(row-i<0||col+i>n-1){
            break;
        }
        if(chess[row-i][col+i]==1){
            return false;
        }
        
    }
    
    for(int i=0;i<n;i++){//check left-below
        if(row+i>n-1||col-i<0){
            break;
        }
        if(chess[row+i][col-i]==1){
            return false;
        }
    }
    
    
    for(int i=0;i<n;i++){//check right-below
        if(row+i>n-1||col+i>n-1){
            break;
        }
        if(chess[row+i][col+i]==1){
            return false;
        }
    }
    
    return true;
}

//回溯法遞歸
void EightQueen(int row,int col,int **chess)
{
    //temp 2Darray
    int **chess2=new int*[n];
    for(int i=0;i<n;i++)
        chess2[i]=new int[n];
    
    //put last scene to temp 2Darray
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            chess2[i][j]=chess[i][j];
        }
    }
    if(row==n)
    {
        cnt++;
    }
    else
    {
        for(int j=0;j<n;j++)
        {
            if(CanPlace(row, j, chess2))
            {
                chess2[row][j]=1;
                EightQueen(row+1, j, chess2);
                chess2[row][j]=0;
            }
        }
    }
    
}

int main()
{
    cout<<"請輸入n皇后"<<endl;
    cin>>n;
    
    //********************蠻力法
//    int *a=new int[n];
////    int a[8]={4,2,7,3,6,8,5,1};
//    double start=clock();
//    queen(a, 0);
//    double end=clock();
//    printf("%f",end-start);
//    cout<<endl;
    //*********************
    
    
    
    //回溯法************
    int **chess=new int*[n];
    for(int i=0;i<n;i++)
        chess[i]=new int[n];
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            chess[i][j]=0;
    double start=clock();

      EightQueen(0, 0, chess);
    double end=clock();
    printf("%f\n",end-start);
    //******************
    return 1;
}

八皇后02.gif

[圖片上傳中...(八皇后.gif-9e5819-1509702099883-0)]

五、下面是枚舉法實現(xiàn)ios動態(tài)尋找解的界面
實現(xiàn)的語言:oc和c++

//
//  ViewController.m
//  八皇后問題
//
//  Created by tao on 2017/10/27.
//  Copyright ? 2017年 LiuTao. All rights reserved.
//

#import "ViewController.h"
#include<iostream>
using namespace std;
@interface ViewController ()

@property(nonatomic,strong)NSMutableArray *array;

@property(nonatomic,assign)int g_count;

@property(nonatomic,assign)int n;

@property(nonatomic,strong)UILabel *l;

@property(nonatomic,strong)UILabel *text;

@end

@implementation ViewController

-(NSMutableArray *)array
{
    if(_array==nil)
    {
        _array=[NSMutableArray array];
    }
    return _array;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self start];
    
    cout<<_g_count<<endl;
    
}



-(void)start
{
    _g_count=0;
    _n=8;
    _l=[[UILabel alloc]init];
    self.view.backgroundColor=[UIColor grayColor];
    int i,j;
    for(i=0;i<_n;i++)
    {
        for(j=0;j<_n;j++)
        {
            
            UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(30+j*40, 80+i*40, 40, 40)];
            label.layer.borderColor=[[UIColor blackColor]CGColor];
            label.layer.borderWidth=1;
            label.backgroundColor=[UIColor whiteColor];
            label.layer.masksToBounds=YES;
            label.tag=i*_n+j+1;
            label.userInteractionEnabled=YES;
            [self.array addObject:label];
            [self.view addSubview:label];
            
        }
    }
    [self begin];
}

-(void)begin
{
    _text=[[UILabel alloc]initWithFrame:CGRectMake(40, 500, 300, 100)];
    _text.backgroundColor=[UIColor whiteColor];
    _text.text=@"八皇后第一次解";
    _text.textAlignment=NSTextAlignmentCenter;
    _text.font=[UIFont systemFontOfSize:20];
    _text.textColor=[UIColor blackColor];
    [self.view addSubview:_text];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        int *a=new int[8];
        [self queen:a and1:0 ];
  });
}



-(int) check:(int *)a and1:(int)n
{
    int i,j;
    for(i=2;i<=n;i++)
    {
        for(j=1;j<=i-1;j++)
        {
            if(a[i]==a[j]||(abs(a[i]-a[j])==abs(i-j)))
                return 0;
        }
    }
    return 1;
    
}

-(bool) judge:(int*)a
{
    for(int i=0;i<8;i++)
    {
        for(int j=i+1;j<8;j++)
        {
            if(abs(a[j] - a[i]) == abs(j-i)||a[j] == a[i])
                return false;
        }
    }
    return true;
}

-(void)queen:(int*)a and1:(int)temp
{
    if(temp==8)
    {
       if([self judge:a])
       {
           dispatch_async(dispatch_get_main_queue(), ^{
               
               NSString *str=[NSString stringWithFormat:@"八皇后的第%d次解",_g_count];
               _text.text=str;
               [NSThread sleepForTimeInterval:2];
               
           });
           _g_count++;
       }
    }
    else
    {
        for(int i=0;i<8;i++)
        {
            a[temp]=i;
            dispatch_async(dispatch_get_main_queue(), ^{
            _l=[_array objectAtIndex:temp*8+i];
            _l.backgroundColor=[UIColor blackColor];
            });
            [NSThread sleepForTimeInterval:0.2];
            [self queen:a and1:temp+1];
            dispatch_async(dispatch_get_main_queue(), ^{
                _l=[_array objectAtIndex:temp*8+i];
                _l.backgroundColor=[UIColor whiteColor];
            });

        }
    }
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


六、下面是回溯法實現(xiàn)ios動態(tài)尋找解的界面
實現(xiàn)的語言:oc和c++


八皇后.gif
//
//  ViewController.m
//  八皇后問題![八皇后.gif](http://upload-images.jianshu.io/upload_images/5196732-f9996aaa1b320560.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

//
//  Created by tao on 2017/10/27.
//  Copyright ? 2017年 LiuTao. All rights reserved.
//

#import "ViewController.h"
#include<iostream>
using namespace std;
@interface ViewController ()

@property(nonatomic,strong)NSMutableArray *array;

@property(nonatomic,assign)int g_count;

@property(nonatomic,assign)int n;

@property(nonatomic,strong)UILabel *l;

@property(nonatomic,strong)UILabel *text;

@end

@implementation ViewController

-(NSMutableArray *)array
{
    if(_array==nil)
    {
        _array=[NSMutableArray array];
    }
    return _array;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self start];

}



-(void)start
{
     _g_count=1;
    _n=8;
    _l=[[UILabel alloc]init];
    self.view.backgroundColor=[UIColor grayColor];
    int i,j;
    for(i=0;i<_n;i++)
    {
        for(j=0;j<_n;j++)
        {
            
            UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(30+j*40, 80+i*40, 40, 40)];
            label.layer.borderColor=[[UIColor blackColor]CGColor];
            label.layer.borderWidth=1;
            label.backgroundColor=[UIColor whiteColor];
            label.layer.masksToBounds=YES;
            label.tag=i*_n+j+1;
            label.userInteractionEnabled=YES;
            [self.array addObject:label];
            [self.view addSubview:label];
            
        }
    }
    [self begin];
}

-(void)begin
{
    _text=[[UILabel alloc]initWithFrame:CGRectMake(40, 500, 300, 100)];
    _text.backgroundColor=[UIColor whiteColor];
    _text.text=@"八皇后第一次解";
    _text.textAlignment=NSTextAlignmentCenter;
    _text.font=[UIFont systemFontOfSize:20];
    _text.textColor=[UIColor blackColor];
    [self.view addSubview:_text];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        int **chess=new int*[_n];
        for(int i=0;i<_n;i++)
            chess[i]=new int[_n];
        
        for(int i=0;i<_n;i++)
            for(int j=0;j<_n;j++)
                chess[i][j]=0;
        
        [self EightQueen:0 and1:0 and2:chess];
    });
}

-(bool) CanPlace:(int)row and1:(int)col and2:(int **)chess
{
    for(int i=0;i<_n;i++){
        if(chess[i][col]==1){//check col
            return false;
        }
        if(chess[row][i]==1){//check row
            return false;
        }
    }
    
    
    for(int i=0;i<_n;i++){//check left-front
        if(row-i<0||col-i<0){
            break;
        }
        if(chess[row-i][col-i]==1){
            return false;
        }
    }
    
    
    for(int i=0;i<_n;i++){//check right-front
        if(row-i<0||col+i>_n-1){
            break;
        }
        if(chess[row-i][col+i]==1){
            return false;
        }
        
    }
    
    for(int i=0;i<_n;i++){//check left-below
        if(row+i>_n-1||col-i<0){
            break;
        }
        if(chess[row+i][col-i]==1){
            return false;
        }
    }
    
    
    for(int i=0;i<_n;i++){//check right-below
        if(row+i>_n-1||col+i>_n-1){
            break;
        }
        if(chess[row+i][col+i]==1){
            return false;
        }
    }
    
    return true;
}

-(void) EightQueen:(int)row and1:(int)col and2:(int **)chess
{
    //temp 2Darray
    int **chess2=new int*[_n];
    for(int i=0;i<_n;i++)
        chess2[i]=new int[_n];
    
    //put last scene to temp 2Darray
    for(int i=0;i<_n;i++)
    {
        for(int j=0;j<_n;j++)
        {
            chess2[i][j]=chess[i][j];
        }
    }
    if(row==_n)
    {
        _g_count++;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSString *str=[NSString stringWithFormat:@"八皇后的第%d次解",_g_count];
            _text.text=str;
            [NSThread sleepForTimeInterval:2];
           
        });
        
        cout<<_g_count<<endl;
    }
    else
    {
        for(int j=0;j<_n;j++)
        {
            if([self CanPlace:row and1:j and2:chess2])
            {
            chess2[row][j]=1;
            dispatch_async(dispatch_get_main_queue(), ^{
                _l=[_array objectAtIndex:row*_n+j];
                _l.backgroundColor=[UIColor blackColor];
               // [NSThread sleepForTimeInterval:1];
            });
            [NSThread sleepForTimeInterval:0.2];
            [self EightQueen:row+1 and1:j and2:chess2];
            
            chess2[row][j]=0;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                _l=[_array objectAtIndex:row*_n+j];
                _l.backgroundColor=[UIColor whiteColor];
           
            });
             [NSThread sleepForTimeInterval:0.2];
           
             }
        
         }
     }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,037評論 4 61
  • 偶遇~我喜歡這個詞,不是故意而為之,是不經(jīng)意間的相遇,你我四目相對的那一刻,怦然而心動! 即使擦肩而過,偶遇得那一...
    微微人生閱讀 314評論 0 0
  • 圣誕節(jié)的清晨,七點醒后又睡了,又是在美夢中醒來。 今天特別想聽杜月笙的故事,因為是我男神的偶像,哈哈,于是在喜馬...
    朱雨哲閱讀 152評論 0 0
  • 參加杭杭的訓(xùn)練營已經(jīng)兩個星期了,這個星期的作業(yè)比上一周要復(fù)雜些,但是基本的畫法原理還是想通的,重要的還是定位。 萌...
    小源寶1573閱讀 357評論 2 0
  • 1 昨天晚上帶Lynn小朋友出去跳廣場舞,倍感欣慰。 過去的幾個月的時間,除了天氣原因和一些其他客觀因素,每天晚上...
    邑曉閱讀 401評論 0 2

友情鏈接更多精彩內(nèi)容