Java Maze problem

Source: Internet
Author: User

Input

A NXM two-dimensional array that represents a maze. The data guarantee has a unique solution, regardless of the case of multiple solutions, that is, the maze has only one channel.

Output

The shortest path in the upper-left corner to the lower-right corner, formatted as shown in the sample.

Sample Input

0 1 0) 0 0

0 1 0) 1 0

0 0 0) 0 0

0 1 1) 1 0

0 0 0) 1 0

Sample Output

(0, 0)

(1, 0)

(2, 0)

(2, 1)

(2, 2)

(2, 3)

(2, 4)

(3, 4)

(4, 4)

ImportJava.util.*; Public classMain { Public Static voidMain (string[] args) {Scanner Scanner=NewScanner (system.in);  while(Scanner.hasnext ()) {intm =Scanner.nextint (); intn =Scanner.nextint (); int[] Map =New int[M][n]; int[] visited =New int[M][n];  for(inti=0;i<m;i++)                 for(intj=0;j<n;j++) Map[i][j]=Scanner.nextint (); //Four Directions            int[] dir = {{1,0},{0,1},{0,-1},{-1,0}}; Stack<Node> Path =NewStack<>(); Node Start=NewNode (0, 0); Node End=NewNode (M-1, n-1); visited[0][0]=1;            Path.push (start);  while(!Path.empty ()) {                Booleanflag=false; Node Peek=Path.peek (); if(Peek.x==end.x && peek.y==end.y) Break; Else                {                     for(inti=0;i<4;i++) {Node ne=NewNode (Peek.x+dir[i][0], peek.y+dir[i][1]); if(ne.x>=0 && ne.x<m && ne.y>=0 && ne.y<n &&Map[ne.x][ne.y]==0 && visited[ne.x][ne.y]==0) {Path.push (NE); VISITED[NE.X][NE.Y]=1; Flag=true;  Break; }                    }                    //Find a direction                    if(flag) {Continue; }                    //there's no direction .Path.pop (); }} Iterator<Node> it =Path.iterator ();  while(It.hasnext ()) {Node Outnode=It.next (); System.out.println ("(" +outnode.x+ "," +outnode.y+ ")");    }} scanner.close (); }    }classnode{intx; inty; Node (intXinty) { This. x =x;  This. y =y; }}

Java Maze problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.