广度优先搜索

作者: 狼牙战士 | 来源:发表于2017-06-06 15:18 被阅读40次
    SYJ.png

    广度优先搜索回答两类问题:

        1.从节点A出发,有前往节点D的路径吗?
        2.从节点A出发,前往节点D的哪条路径最短?
    

    演示:

    SYJ.png

    代码演示

    OC实现代码:

    //示例:是否存在A到D的路径
    #import "ViewController.h"
    
    @interface ViewController ()
    @property(nonatomic,strong)NSDictionary *dic;
    @end
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        _dic = [[NSDictionary alloc] init];
        //把每个节点对应的邻居节点存储起来
        _dic = @{@"A":@[@"B",@"F"],@"B":@[@"C"],@"C":@[@"D"],@"D":@[],@"E":@[@"C"],@"F":@[@"E",@"G"],@"G":@[@"C"]};
        BOOL lj = [self search:@"D"];
        if(lj){
            NSLog(@"存在A到D的路径");
        }else{
            NSLog(@"不存在A到D的路径");
        }
    }
    
    -(BOOL)search:(NSString*)str{
        //查找队列
        NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
        [array addObject:@"A"];
        //存储已经检查过的节点
        NSMutableArray *searchedArr = [[NSMutableArray alloc] initWithCapacity:0];
        //当查找队列不为空
        while ([array count] != 0) {
            //取出队列中的一个元素
            NSString *name = array[0];
            [array removeObjectAtIndex:0];
            //检查这个元素是否被检查过
            if(![searchedArr containsObject:name]){
                //检查是不是要找的节点
                if([name isEqualToString:str]){
                    return YES;
                }else{
                    //将这个节点对应的邻居节点加入查找队列
                    [array addObjectsFromArray:[_dic objectForKey:name]];
                    //将这个节点标记为已检查过
                    [searchedArr addObject:name];
                }
            }
        }
        return NO;
    }
    @end
    

    java代码实现:

    
    import java.util.*;
    public class MyClass {
        private static Map m1 = new HashMap();
        public static void main(String[] args){
            //把每个节点对应的邻居节点存储起来
            m1.put("A", new String[]{"B", "F"});
            m1.put("B", new String[]{"C"});
            m1.put("C", new String[]{"D"});
            m1.put("D", new String[]{});
            m1.put("E", new String[]{"C"});
            m1.put("F", new String[]{"E","G"});
            m1.put("G", new String[]{"C"});
    
            boolean lj = search("G");
            if(lj){
                System.out.println("cz");
            }else{
                System.out.println("bcz");
            }
        }
    
        private static boolean search(String str){
            //查找队列
            Queue<String> queue = new LinkedList<String>();
            queue.offer("A");
            //存储已经检查过的节点
            String[] searchedArray = new String[0];
            //当查找队列不为空
            while (queue.size() != 0){
                //取出队列中的一个元素
                String name = queue.poll();
                //检查这个元素是否被检查过
                if(!Arrays.asList(searchedArray).contains(name)){
                    //检查是不是要找的节点
                    if(name == str){
                        return true;
                    }else{
                        //将这个节点对应的邻居节点加入查找队列
                        String[] s = (String[]) m1.get(name);
                        for(int i = 0;i<s.length;i++){
                            queue.offer(s[i]);
                        }
                        //将这个节点标记为已检查过
                        searchedArray = Arrays.copyOf(searchedArray,searchedArray.length+1);
                        searchedArray[searchedArray.length-1] = name;
                    }
                }
            }
            return false;
        }
    }
    

    python实现代码:

    from collections import deque
    def search(str):
        queue = deque()
        queue += 'A'
        searched = []
        while queue:
            name = queue.popleft()
            if not name in searched:
                if name == str:
                    return True
                else:
                    queue += dict[name]
                    searched.append(name)
        return False
    
    dict = {'A':['B','F'],'B':['C'],'C':['D'],'D':[],'E':['C'],'F':['E','G'],'G':['C']}
    if search('D'):
        print('cz')
    else:
        print('bcz')
    

    相关文章

      网友评论

        本文标题:广度优先搜索

        本文链接:https://www.haomeiwen.com/subject/eahgfxtx.html