深度优先搜索(DFS)

深度优先搜索算法:优先向下层进行状态扩展

搜索过程:

从一个顶点开始,如果该结点下层能够继续扩展,则向下层进行状态扩展,如果下层不能够继续扩展,寻找本层未处理过的结点,继续向下层状态进行扩展

用一个经典的例子(走迷宫)来感受下

给定一个二维数组 int a[10][10] = {0 , 1 , 0 , 0 , 0

                 0 , 1 , 0 , 1 , 0

                 0 , 0 , 0 , 0 , 0

                 0 , 1 , 1 , 1 , 0

                 0 , 0 , 0 , 1 , 0 } ;

它表示一个迷宫,其中“1”代表墙,“0”代表通路,只能横着走或竖着走,要求编写程序找出从左上角到右下角的最短路径的长度

#include<iostream>
#include<stdio.h>
using namespace std ;

typedef struct Node {
    int x , y ;
    int step ;
} Node ;

int m , n ;

bool is_ok(Node cur)    {
    if(cur.x < 0 || cur.x >= m || cur.y < 0 || cur.y >= n)
        return false ;
    return true ;
}


int dx[] = {0 , 1} ;
int dy[] = {1 , 0} ;

int map[10][10] ;

int visit[10][10] = {0} ;

bool flag = false ;
void dfs(Node cur)    {
    if(cur.x == n - 1 && cur.y == m - 1)    {
        cout << cur.step << endl ;
        flag = true ;
        return ;
    }
    for(int i = 0 ; i < 2 ; i++)    {
        Node next ;
        next.x = cur.x + dx[i] ;
        next.y = cur.y + dy[i] ;
        if(map[next.x][next.y] != 1 && visit[next.x][next.y] != 1 && is_ok(next))    {
            visit[next.x][next.y] = 1 ;
            next.step = cur.step + 1 ;
            dfs(next) ;
            if(flag == true)
                return ;
            visit[next.x][next.y] = 0 ;
        }
    }
}
    
int main()    {
    cin >> m >> n ;
    for(int i = 0 ; i < m ; i++)
        for(int j = 0 ; j< n ; j++)
            cin >> map[i][j] ;
    Node cur ;
    cur.x = 0 , cur.y = 0 , cur.step = 0 ;
    visit[0][0] = 1 ;
    dfs(cur) ;
    return 0 ;
}

 

posted @ 2015-04-20 21:03  scott_dingg  阅读(630)  评论(0编辑  收藏  举报