Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class SpiralMatrix
- {
- private static void ChangeDir(ref string dir) {
- if (dir == "Right"){
- dir = "Down";
- }else if (dir == "Down") {
- dir = "Left";
- }else if(dir == "Left"){
- dir = "Up";
- }else{
- dir = "Right";
- }
- }
- static void Main(string[] args)
- {
- int n = int.Parse(Console.ReadLine());
- int top = 0;
- int left = 0;
- int bottom = n - 1;
- int right = n - 1;
- int counter = 1;
- string dir = "Right";
- int[,] arr = new int[n,n];
- while (top <= bottom && left <= right)
- {
- if (dir == "Right") {
- for (int i = left; i <= right; i++)
- {
- arr[top, i] = counter++;
- }
- top++;
- ChangeDir(ref dir);
- }
- else if (dir == "Down") {
- for (int i = top; i <= bottom; i++)
- {
- arr[i, right] = counter++;
- }
- right--;
- ChangeDir(ref dir);
- }
- else if (dir == "Left"){
- for (int i = right; i >= left; i--)
- {
- arr[bottom, i] = counter++;
- }
- bottom--;
- ChangeDir(ref dir);
- }
- else {
- for (int i = bottom; i >= top; i--)
- {
- arr[i, left] = counter++;
- }
- left++;
- ChangeDir(ref dir);
- }
- }
- for (int i = 0; i < n; i++){
- for (int j = 0; j < n; j++) {
- Console.Write("{0} ", arr[i,j].ToString().PadRight(3, ' '));
- }
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement