/*
* File name : maze.cpp
* Function : 迷宫问题 求解 C++实现
* Created on : 2016年5月15日
* Author : beijiwei@qq.com
* Copyright : 欢迎大家和我一起交流学习,转载请保持源文件的完整性。
任何单位和个人不经本人允许不得用于商业用途
*
题目: 多条路径 求解路径条数, 若有回环,则只有 向右和向下
10 10
1 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1
0 0 1 0 0 1 0 1 0 1
0 0 1 1 1 1 0 1 0 1
0 0 1 0 0 0 0 1 0 1
0 0 1 0 1 1 1 1 0 1
0 0 1 0 1 0 0 1 0 1
0 0 1 1 1 0 0 1 1 1
0 0 0 0 0 0 0 0 1 1
*
*/
#include <cstdio>
#include <iostream>
using namespace std;
typedef struct {
int data;
bool mark;
int x;
int y;
}Spot;
#define SIZE 10
Spot sarray[SIZE][SIZE];
void bfs(int x,int y);
int path_count=0;
int main(int argc, char** argv)
{
int M = 0, N = 0;
freopen("input.txt", "r", stdin);
cin >> M >> N;
for (int i = 0; i<M; i++)
for (int j = 0; j < N; j++) {
cin >> sarray[i][j].data; // get input data
sarray[i][j].mark = 0;
sarray[i][j].x = i;
sarray[i][j].y = j;
}
bfs(0,0);
cout<<"path count is "<<path_count<<endl;
return 0;
}
int offset[4][2]={-1,0,0,1,1,0,0,-1};
bool get_one_flag=false;
void bfs(int x,int y)
{
int tmpx,tmpy,count=0;
sarray[x][y].mark=true;
cout<<x<<" "<<y<<endl;
if(x==9 && y==9)
{
get_one_flag=true;
path_count++;
return;
}
for(int k=0;k<4;k++){
tmpx=x+offset[k][0];
tmpy=y+offset[k][1];
if( tmpx >=0 && tmpx < SIZE &&
tmpy >=0 && tmpy < SIZE &&
sarray[tmpx][tmpy].data==1 &&
sarray[tmpx][tmpy].mark==false)
{
count++;
}
}
if(count==0){//no road
for(int k=0;k<4;k++){
tmpx=x+offset[k][0];
tmpy=y+offset[k][1];
if( tmpx >=0 && tmpx < SIZE &&
tmpy >=0 && tmpy < SIZE &&
sarray[tmpx][tmpy].data==1)
{
count++;
}
}
if(count >0){//无路时,只要该点上下左右有为1的点,说明增加一条通道
path_count++;
count=0;
}
}
for(int k=0;k<4;k++){
tmpx=x+offset[k][0];
tmpy=y+offset[k][1];
if( tmpx >=0 && tmpx < SIZE &&
tmpy >=0 && tmpy < SIZE &&
sarray[tmpx][tmpy].data==1)
{
if(sarray[tmpx][tmpy].mark==false){
bfs(tmpx,tmpy);
}
}
}
}
经典算法迷宫问题 3.多条路径 BFS求解 C++实现
原文作者:迷宫问题
原文地址: https://blog.csdn.net/beijiwei/article/details/51419266
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/beijiwei/article/details/51419266
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。