• 用深度优先搜索解迷宫问题


    定义一个二维数组:

    int maze[5][5] = {
    	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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的路线。程序如下:

    //By LYLtim
    
    #include<stdio.h>
    #include<stdlib.h>
    
    const char
    	Di[4] = {0,1,0,-1},
    	Dj[4] = {1,0,-1,0};
    
    char maze[5][5] = {
    	2, 1, 0, 0, 0,
    	0, 1, 0, 1, 0,
    	0, 0, 0, 0, 0,
    	0, 1, 1, 1, 0,
    	0, 0, 0, 1, 0},
    	ip = 0;
    
    struct {char i, j;} path[23];
    
    void print_maze(void)
    {
    	char i, j;
    	for (i = 0; i < 5; i++) {
    		for (j = 0; j < 5; j++)
    			printf("%hd ", maze[i][j]);
    		putchar('\n');
    	}
    	printf("*********\n");
    }
    
    void print_path(void)
    {
    	char i = 0;
    	printf("(0,0)");
    	for (i = 0; i < ip; i++)
    		printf("->(%hd,%hd)", path[i].i, path[i].j);
    	exit(0);
    }
    
    void try(char i, char j)
    {
    	char k;
    	for (k = 0; k < 4; k++) {
    		char Ni = i + Di[k], Nj = j + Dj[k];
    		if (Ni >= 0 && Ni <5 && Nj >= 0 && Nj < 5 && maze[Ni][Nj] == 0) {
    			maze[Ni][Nj] = 2;
    			path[ip++].i = Ni; path[ip].j = Nj;
    			print_maze();
    			if (Ni == 4 && Nj == 4)
    				print_path();
    			else
    				try(Ni, Nj);
    			maze[Ni][Nj] = 0;
    			path[--ip].i = 0; path[ip].j = 0;
    		}
    	}
    }
    		
    
    int main(void)
    {
    	try(0, 0);
    	return 0;
    }

    运行结果如下:

    2 1 0 0 0 
    2 1 0 1 0
    0 0 0 0 0
    0 1 1 1 0
    0 0 0 1 0
    *********
    2 1 0 0 0
    2 1 0 1 0
    2 0 0 0 0
    0 1 1 1 0
    0 0 0 1 0
    *********
    2 1 0 0 0
    2 1 0 1 0
    2 2 0 0 0
    0 1 1 1 0
    0 0 0 1 0
    *********
    2 1 0 0 0
    2 1 0 1 0
    2 2 2 0 0
    0 1 1 1 0
    0 0 0 1 0
    *********
    2 1 0 0 0
    2 1 0 1 0
    2 2 2 2 0
    0 1 1 1 0
    0 0 0 1 0
    *********
    2 1 0 0 0
    2 1 0 1 0
    2 2 2 2 2
    0 1 1 1 0
    0 0 0 1 0
    *********
    2 1 0 0 0
    2 1 0 1 0
    2 2 2 2 2
    0 1 1 1 2
    0 0 0 1 0
    *********
    2 1 0 0 0
    2 1 0 1 0
    2 2 2 2 2
    0 1 1 1 2
    0 0 0 1 2
    *********
    (0,0)->(1,0)->(2,0)->(2,0)->(2,1)->(2,2)->(2,3)->(3,4)->(4,4)
  • 相关阅读:
    Codeforces Round #362 (Div. 2) C
    poj1655 树重心
    poj1985 树直径
    Codeforces Round #403 (based on Technocup 2017 Finals)
    uva 10054 The necklacr
    bfs codeforces 754B Ilya and tic-tac-toe game
    矩阵快速幂专题
    CodeForces 863E Turn Off The TV 思维,扫描线
    CodeForces 803F Coprime Subsequences 莫比乌斯,容斥
    CodeForces 803C Maximal GCD 思维
  • 原文地址:https://www.cnblogs.com/LYLtim/p/2212844.html
Copyright © 2020-2023  润新知