Created
September 3, 2013 08:12
-
-
Save w00lf/6420988 to your computer and use it in GitHub Desktop.
**************Спираль*************
http://acmp.ru/index.asp?main=task&id_task=196 - таже задача, сильно отрефакторенный прмиер на основе кода python.
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; | |
| n2 = (int)Math.pow(n, 2); | |
| dx = 1; | |
| dy = x = y = 0; | |
| 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{ | |
| temp = dx; | |
| dx = -dy; | |
| dy = temp; | |
| x = x + dx; | |
| y = y + dy; | |
| } | |
| } | |
| 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