八皇后和N皇后以及ios实现界面动态寻找解

一、用枚举法实现
思路:枚举所有的可能来,可以看成一个树形结构,到了叶子节点再去判断是不是可行解

二、用回溯法实现
思路:在枚举法的基础上先进行判断是不是可以放的点,再去进行递归

三、实现用了2种方法,一个是一维数组,一个是二维数组。一维数组中数组下标为皇后坐标的行,数组中对应的值为皇后坐标的列

四、以下是代码部分,并且实现了动态寻找解(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)]

五、下面是枚举法实现ios动态寻找解的界面
实现的语言: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


六、下面是回溯法实现ios动态寻找解的界面
实现的语言: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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,614评论 4 59
  • 偶遇~我喜欢这个词,不是故意而为之,是不经意间的相遇,你我四目相对的那一刻,怦然而心动! 即使擦肩而过,偶遇得那一...
    微微人生阅读 289评论 0 0
  • 圣诞节的清晨,七点醒后又睡了,又是在美梦中醒来。 今天特别想听杜月笙的故事,因为是我男神的偶像,哈哈,于是在喜马...
    朱雨哲阅读 83评论 0 0
  • 参加杭杭的训练营已经两个星期了,这个星期的作业比上一周要复杂些,但是基本的画法原理还是想通的,重要的还是定位。 萌...
    小源宝1573阅读 270评论 2 0
  • 1 昨天晚上带Lynn小朋友出去跳广场舞,倍感欣慰。 过去的几个月的时间,除了天气原因和一些其他客观因素,每天晚上...
    邑晓阅读 349评论 0 2