Created
September 3, 2013 10:51
-
-
Save w00lf/6422381 to your computer and use it in GitHub Desktop.
**********Змейка************
http://acmp.ru/index.asp?main=task&id_task=197
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.*; | |
| import java.math.BigInteger; | |
| import java.util.*; | |
| public class Main{ | |
| public static void main(String[] argv) throws IOException,Exception{ | |
| new Main().run(); | |
| } | |
| public static StreamTokenizer sc ; | |
| public static int[][] arr; | |
| public static int n; | |
| public static int nextInt() throws Exception{ | |
| sc.nextToken(); | |
| return (int)sc.nval; | |
| } | |
| public void run() throws IOException,Exception{ | |
| sc = new StreamTokenizer(new BufferedReader(new FileReader("input.txt"))); | |
| n = nextInt(); | |
| int dx, dy, n2, x, y, nx, ny, temp, line; | |
| n2 = (int)Math.pow(n, 2); | |
| dy = 1; | |
| dx = -1; | |
| x = y = 0; | |
| line = 1; | |
| arr = new int[n][n]; | |
| for (int i = 1; i < n2+1; i++) { | |
| arr[y][x] = i; | |
| nx = x + dx; | |
| ny = y + dy; | |
| if (isValid(nx) && isValid(ny) && arr[ny][nx] == 0) { | |
| x = nx; | |
| y = ny; | |
| }else{ | |
| if (line % 2 == 0) { | |
| if (isValid(x+1)) { | |
| x++; | |
| }else if (isValid(y+1)){ | |
| y++; | |
| } | |
| }else { | |
| if (isValid(y+1)) { | |
| y++; | |
| }else if (isValid(x+1)){ | |
| x++; | |
| } | |
| } | |
| temp = dx; | |
| dx = dy; | |
| dy = temp; | |
| line ++; | |
| } | |
| } | |
| PrintWriter pw = new PrintWriter(new File("output.txt")); | |
| for (int[] row : arr) { | |
| for (int elem : row) { | |
| pw.printf("%6d", elem); | |
| } | |
| pw.println(); | |
| } | |
| pw.close(); | |
| } | |
| public static Boolean isValid(int i) { | |
| if (i >= 0 && i < n) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment