水管工游戏

匿名 (未验证) 提交于 2019-12-02 21:53:52

原创

import java.util.*;  public class 水管工游戏 {          static int count=0;     static int flag=0;     static int n;     static int m;     static int maze[][];     static int book[][];     static ArrayList listx=new ArrayList();     static ArrayList listy=new ArrayList();          static void dfs(int x,int y,char way) {    //way代表入水口         if(x==n-1 && y==m) {    //成功判断             flag=1;             return;         }         if(x<0 || x>n-1 || y<0 || y>m-1) {    //越界判断             return;         }         if(maze[x][y]==0 || book[x][y]==1) {    //树木与访问判断             return;         }         book[x][y]=1;         listx.add(x);         listy.add(y);         count++;         if(maze[x][y]==5 || maze[x][y]==6) {    //直管             if(way=='l') {    //左                 dfs(x,y+1,'l');             }             if(way=='r') {    //右                 dfs(x,y-1,'r');             }             if(way=='u') {    //上                 dfs(x+1,y,'u');             }             if(way=='d') {    //下                 dfs(x-1,y,'d');             }         }         if(maze[x][y]>=1 && maze[x][y]<=4){    //弯管             if(way=='l') {    //左                 dfs(x-1,y,'d');                 dfs(x+1,y,'u');             }             if(way=='r') {    //右                 dfs(x-1,y,'d');                 dfs(x+1,y,'u');             }             if(way=='u') {    //上                 dfs(x,y-1,'r');                 dfs(x,y+1,'l');             }             if(way=='d') {    //下                 dfs(x,y-1,'r');                 dfs(x,y+1,'l');             }         }         if(flag==1) {             return;         }         book[x][y]=0;    //回溯         listx.remove(count-1);         listy.remove(count-1);         count--;         return;     }      public static void main(String[] args) {         Scanner reader=new Scanner(System.in);         n=reader.nextInt();         m=reader.nextInt();         maze=new int[n][m];         book=new int[n][m];         for(int i=0;i<n;i++) {             for(int j=0;j<m;j++) {                 maze[i][j]=reader.nextInt();                 book[i][j]=0;             }         }         dfs(0,0,'l');         if(flag==1) {             System.out.println("YES");         }         else {             System.out.println("NO");         }         System.out.print("路径为:");         for(int i=0;i<count;i++) {             System.out.print("("+listx.get(i)+","+listy.get(i)+")"+" ");         }     } }

测试用例:

5 4
5 3 5 3
1 5 3 0
2 3 5 1
6 1 1 5
1 5 5 4


YES

11:05:05

2018-07-22

文章来源: 水管工游戏
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!