1072:迷宫

</pre><pre code_snippet_id="294564" snippet_file_name="blog_20140415_1_8888646" name="code" class="cpp">#include <iostream>
#include <cstring>
#define MAXN 100
using namespace std;
void dfs(int x,int y);  //dfs关键算法
char q[MAXN][MAXN];
bool c[MAXN][MAXN];  /**用来记录这个位置是否询问过*/
int n;
bool Count;
int main()
{   int m;
    cin>>m;
    while(m--)
    {
        Count=false; /**先假定没有通路**/
        memset(c,false,sizeof(bool)); /**所有位置都设置为未访问过*/
        cin>>n;
        for(int i=0;i<n;i++)
            for (int j=0;j<n;j++)
            cin>>q[i][j];
        dfs(0,0);             /**从输入的(0,0)位置开始深搜*/
        if (Count==true) cout<<"YES"<<endl;  /**count是判断真假的值*/
        else cout<<"NO"<<endl;
    }
    return 0;
}
void dfs(int x,int y)
{
    c[x][y]=true;  /**如果x,y输入到这个位置,那么它被访问过*/
    if((x+1==n-1 && y==n-1)||(x==n-1 && y+1==n-1))
        /**如果向右走或向下走能走到终点,那么存在通路。由于
        终点在右下角,所以不存在向左或向上走的情况,无需考虑*/
    {
        Count=true ;
        return ;
    }
    /**如果相应的位置未访问过,而且能走,而且未超出规定的边界
     **那么就往相应的位置搜索*/
    if ( c[x][y+1]==0 && q[x][y+1]=='.' && y+1<n ) dfs(x,y+1); //右
    if ( c[x][y-1]==0 && q[x][y-1]=='.' && y-1>=0) dfs(x,y-1); //左
    if ( c[x+1][y]==0 && q[x+1][y]=='.' && x+1<n ) dfs(x+1,y); //下
    if ( c[x-1][y]==0 && q[x-1][y]=='.' && x-1>=0) dfs(x-1,y); //上
}



你可能感兴趣的:(ACM,DFS)