SDUT 1269-走迷宮(DFS列印路徑),sdut1269-

來源:互聯網
上載者:User

SDUT 1269-走迷宮(DFS列印路徑),sdut1269-

走迷宮Time Limit: 1000ms   Memory limit: 65536K  有疑問?點這裡^_^題目描述有一個m*n格的迷宮(表示有m行、n列),其中有可走的也有不可走的,如果用1表示可以走,0表示不可以走,輸入這m*n個資料和起始點、結束點(起始點和結束點都是用兩個資料來描述的,分別表示這個點的行號和列號)。現在要你編程找出所有可行的道路,要求所走的路中沒有重複的點,走時只能是上下左右四個方向。如果一條路都不可行,則輸出相應資訊(用-1表示無路)。輸入第一行是兩個數m,n(1< m, n< 15),接下來是m行n列由1和0組成的資料,最後兩行是起始點和結束點。輸出所有可行的路徑,輸出時按照左上右下的順序。描述一個點時用(x,y)的形式,除開始點外,其他的都要用“->”表示。如果沒有一條可行的路則輸出-1。樣本輸入
5 41 1 0 01 1 1 10 1 1 01 1 0 11 1 1 11 15 4
樣本輸出
(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)(1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)(1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
path[]數組儲存路徑。。無腦dfs 
#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>#include <cctype>#include <cstdlib>#include <set>#include <map>#include <vector>#include <string>#include <queue>#include <stack>#include <cmath>#define LL long longusing namespace std;const int INF = 0x3f3f3f3f;struct node{int x,y;}path[1000];int n,m,sx,sy,ex,ey,ok,step;bool vis[16][16],ma[16][16];int dir[4][2]={{0,-1},{-1,0},{0,1},{1,0}};void print(){for(int i=0;i<step-1;i++)printf("(%d,%d)->",path[i].x,path[i].y);printf("(%d,%d)\n",ex,ey);}void dfs(int x,int y){if(x==ex&&y==ey){ok=1;print();return ;}for(int i=0;i<4;i++){int tx=x+dir[i][0];int ty=y+dir[i][1];if(tx>=1&&tx<=m&&ty>=1&&ty<=n&&!vis[tx][ty]&&ma[tx][ty]){path[step].x=tx;path[step++].y=ty;vis[tx][ty]=1;dfs(tx,ty);vis[tx][ty]=0;step--;}}}int main(){while(~scanf("%d%d",&m,&n)){ok=0;memset(path,-1,sizeof(path));memset(vis,0,sizeof(vis));for(int i=1;i<=m;i++)for(int j=1;j<=n;j++)scanf("%d",&ma[i][j]);scanf("%d%d%d%d",&sx,&sy,&ex,&ey);vis[sx][sy]=1;step=0;path[step].x=sx;path[step++].y=sy;dfs(sx,sy);if(!ok)puts("-1");}return 0;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.