http://yuncode.net/code/c_5093587f5dbaf9
该文章使用递归可以寻找出路径,但并未寻找出所有的路径。
#include <stdio.h> #include <stdlib.h> void visit ( int, int ); int maze[7][7] = {{2, 2, 2, 2, 2, 2, 2}, {2, 0, 0, 0, 0, 0, 2}, {2, 0, 2, 0, 2, 0, 2}, {2, 0, 0, 2, 0, 0, 2}, {2, 2, 0, 2, 0, 2, 2}, {2, 0, 0, 0, 0, 0, 2}, {2, 2, 2, 2, 2, 2, 2} }; int startI = 1, startJ = 1; // 入口 int endI = 5, endJ = 5; // 出口 int success = 0; int main ( void ) { int i, j; printf ( "显示迷宫:\n" ); for ( i = 0; i < 7; i++ ) { for ( j = 0; j < 7; j++ ) if ( maze[i][j] == 2 ) printf ( "█" ); else printf ( " " ); printf ( "\n" ); } visit ( startI, startJ ); } void show() { int i, j; printf ( "\n显示路径:\n" ); for ( i = 0; i < 7; i++ ) { for ( j = 0; j < 7; j++ ) { if ( maze[i][j] == 2 ) printf ( "█" ); else if ( maze[i][j] == 1 ) printf ( "◇" ); else printf ( " " ); } printf ( "\n" ); } } void visit ( int i, int j ) { if ( i == endI && j == endJ ) { success = 1; show( ); } if ( maze[i][j] == 0 )//运用回溯法判断 { maze[i][j] = 1; visit( i+1, j); visit( i, j+1); visit( i, j-1); visit( i-1, j); maze[i][j] = 0; } }
修改后可以获得所有的路径。
时间: 2024-10-11 09:21:37