c ++ depth-first search (maze)

maze

Topic background

Given an N * M squares maze, T-maze at the barrier, not through the barrier. Given the start point and end point, Q: After a maximum of 1 per box, how many from the start point to the end point coordinate coordinates the program. In the maze to move up and down about four ways, you can only move one square. No obstacles to ensure data starting point.

Title Description

Input formats:

The first row N, M and T, N row, M being a column, T is the total number of disorders. The second line starting coordinates SX, SY, ending coordinate FX, FY. Then the coordinates of the point T lines, each behavioral disorders.

Output formats:

Given the start point and end point, and asked after each square up to 1 times the total number of programs from the starting point to the end point coordinate coordinates.

Sample input and output

Input Sample # 1

2 2 1
1 1 2 2
1 2

Sample Output # 1

1

Explanation

[Data] scale
1≤N, M≤5

AC Code

#include<bits/stdc++.h>
using namespace std;
int q[101][101];
long long sum=0;
int i,j,n,m,t,sx,sy,x,y,ex,ey;
void dfs(int a,int b)
{
    if (a==ex&&b==ey)//如果找到了终点 
    {
        sum++;//方案数 + 1 
        return;
    }
    else
    {
        q[a][b]=0;//把当前节点置为已选择 
        if(q[a-1][b]!=0) {dfs(a-1,b);q[a-1][b]=1;}
        if(q[a][b-1]!=0) {dfs(a,b-1);q[a][b-1]=1;}
        if(q[a][b+1]!=0) {dfs(a,b+1);q[a][b+1]=1;}
        if(q[a+1][b]!=0) {dfs(a+1,b);q[a+1][b]=1;}//以当前节点为中心向四个方向无限拓展,直到找不到邻节点或碰到障碍物 
    }
}
int main()
{
    memset(q,0,sizeof(q));//初始化棋盘所有节点为不可用 
    cin>>n>>m>>t;//n是行    m是列    t是障碍物的个数 
    cin>>sx>>sy>>ex>>ey;// sx sy是起点的坐标     ex ey是终点的坐标 
    for(i=1;i<=n;i++)
        for(j=1;j<=m;j++)
            q[i][j]=1;//找到迷宫中所有可走的节点  
    for(i=1;i<=t;i++)
    {
        cin>>x>>y;
        q[x][y]=0;//把障碍物标为不可用 
    }
    dfs(sx,sy);//把起点作为入参进行DFS 
    cout<<sum<<endl;//sum是方案总数 
    return 0;
}

Guess you like

Origin www.cnblogs.com/LJA001162/p/11220935.html