Advertisement
sashomaga

using recursion

Jan 10th, 2013
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.63 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. //Write a program that fills and prints a matrix of size (n, n) as shown below: (examples for n = 4)
  4. // 1 12 11 10
  5. // 2 13 16 9
  6. // 3 14 15 8
  7. // 4 5  6  7
  8.  
  9. class Program
  10. {
  11.     static int n = 9; //matriz size
  12.     static int[,] matrix = new int[n, n];
  13.     static int score = 1;
  14.     static void Main()
  15.     {
  16.        
  17.         int pos = 0;
  18.         Recursion(pos);
  19.        
  20.         print(matrix);
  21.     }
  22.  
  23.  
  24.     private static void Recursion(int pos)
  25.     {
  26.         if(pos >= n/2 + 1) //bottom
  27.         {
  28.             return;
  29.         }
  30.         int x;
  31.         int y;
  32.         for (x = pos,y = pos; x< n - pos;x++)
  33.         {
  34.             matrix[x,y] = score++;
  35.         }
  36.         x--;
  37.         for (y = y + 1 ;y < n - pos; y++)
  38.         {
  39.             matrix[x, y] = score++;
  40.         }
  41.         y--;
  42.         for (x = x - 1; x >= 0 + pos; x--)
  43.         {
  44.             matrix[x, y] = score++;
  45.         }
  46.         x++;
  47.         for (y = y - 1; y > 0 + pos; y--)
  48.         {
  49.             matrix[x, y] = score++;
  50.         }
  51.  
  52.         Recursion(pos + 1); //recursive call
  53.  
  54.     }
  55.    
  56.  
  57.     private static void print(int[,] matrix)
  58.     {
  59.         for (int x = 0; x < matrix.GetLength(0); x++)
  60.         {
  61.             for (int y = 0; y < matrix.GetLength(1); y++)
  62.             {
  63.                 if (matrix[x, y] < 10)
  64.                 {
  65.                     Console.Write(" "+matrix[x, y]);
  66.                 }
  67.                 else
  68.                 {
  69.                     Console.Write(matrix[x, y]);
  70.                 }
  71.                
  72.             }
  73.             Console.WriteLine();
  74.         }
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement