Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- //Write a program that fills and prints a matrix of size (n, n) as shown below: (examples for n = 4)
- // 1 12 11 10
- // 2 13 16 9
- // 3 14 15 8
- // 4 5 6 7
- class Program
- {
- static int n = 9; //matriz size
- static int[,] matrix = new int[n, n];
- static int score = 1;
- static void Main()
- {
- int pos = 0;
- Recursion(pos);
- print(matrix);
- }
- private static void Recursion(int pos)
- {
- if(pos >= n/2 + 1) //bottom
- {
- return;
- }
- int x;
- int y;
- for (x = pos,y = pos; x< n - pos;x++)
- {
- matrix[x,y] = score++;
- }
- x--;
- for (y = y + 1 ;y < n - pos; y++)
- {
- matrix[x, y] = score++;
- }
- y--;
- for (x = x - 1; x >= 0 + pos; x--)
- {
- matrix[x, y] = score++;
- }
- x++;
- for (y = y - 1; y > 0 + pos; y--)
- {
- matrix[x, y] = score++;
- }
- Recursion(pos + 1); //recursive call
- }
- private static void print(int[,] matrix)
- {
- for (int x = 0; x < matrix.GetLength(0); x++)
- {
- for (int y = 0; y < matrix.GetLength(1); y++)
- {
- if (matrix[x, y] < 10)
- {
- Console.Write(" "+matrix[x, y]);
- }
- else
- {
- Console.Write(matrix[x, y]);
- }
- }
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement