Simple implementation code for the Java Serpentine array

Source: Internet
Author: User

Chat with friends on Friday talk about a serpentine array of Java implementations, the proposition is: Suppose a two-dimensional array width W high h, starting from 1 serpentine output .

int[][] Numbermatric = new Int[w][h];

At that time nap past mind bag is not clear, Leng no good ideas. Later in the evening study, found a relatively simple way to achieve. The core ideas are:

To find the direction of movement, the two-dimensional array is filled in ascending order of movement.

A relatively simple implementation is as follows:

    Private voidSnakematric (intWinth) {        intx, y;//x, y coordinates.         int[] Numbermatric =New int[W][h]; intnum = numbermatric[x = 0][y = 0] = 1;  while(Num < w*h) {            //Move Right             while(Y+1 < w && numbermatric[x][y+1] = = 0/ * When an array of items is not populated,its default value is 0*/) {y++; Numbermatric[x][y]= ++num; }            //Move Down             while(x+1

) {x++; Numbermatric[x][y]= ++num; } //Move left while(y-1>=0 && numbermatric[x][y-1] = = 0) {y--; Numbermatric[x][y]= ++num; } //Move Upward while(x-1>=0 && numbermatric[x-1][y] = = 0) {x--; Numbermatric[x][y]= ++num; } } //Print Output for(x = 0;x < w;x++){ for(y = 0;y < h;y++) {System.out.printf ("%4d", Numbermatric[x][y]); } System.out.println ();//line Break } }

Simple implementation code for the Java Serpentine array

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.