weinan030416

导航

走迷宫

@起点,.终点,1障碍,0可以走,输出路径

#include <iostream>
using namespace std;

int dx[4]={0,0,1,-1},dy[4]={1,-1,0,0};
int startx,starty,endx,endy,w,l; 
char puzzle[10][10];//最多支持10*10迷宫 
bool walked[10][10];
struct point
{
    int x;
    int y;
};
point path[100];

void dfs(int x,int y,int cnt)
{    
    path[cnt].x=x;//记录路径 
    path[cnt].y=y;
    cnt++;
    walked[x][y]=true;//标记走过
    
    if(x==endx&&y==endy)//走到终点 
    {
        for(int i=0;i<cnt-1;i++)
        cout<<path[i].x<<","<<path[i].y<<"->";
        cout<<path[cnt-1].x<<","<<path[cnt-1].y<<endl;
        return;
    }
    bool t=false;
    for(int k=0;k<4;k++)
    {
        int tx=x+dx[k],ty=y+dy[k];
        if(puzzle[tx][ty]!='1'&&walked[tx][ty]==false&&tx>=0&&ty>=0&&tx<w&&ty<l)//可以走 
        {
            t=true;
            dfs(tx,ty,cnt); 
            walked[tx][ty]=false; 
        }
    }
    if(!t)//无路可走 
    return;
}
 
int main()
{
    cin>>w>>l;
    for(int i=0;i<w;i++)
        for(int j=0;j<l;j++)
        {
            cin>>puzzle[i][j];
            //0可以走,1障碍,@起点,.终点 
            if(puzzle[i][j]=='@')
            {
                startx=i;
                starty=j;
            }
            if(puzzle[i][j]=='.')
            {
                endx=i;
                endy=j;
            }
        }
    dfs(startx,starty,0);    
}

 最大岛屿面积

1陆地  0海洋

 

posted on 2023-02-02 13:53  楠030416  阅读(30)  评论(0编辑  收藏  举报