Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace backtracking_konj_u_sahu
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- int tableDimension = 5;
- int[,] table = new int[tableDimension, tableDimension];
- int[,] moves = new int[,]{
- { -2, -1 }, { -2, 1 }, //left
- { -1, -2 }, { 1, -2 }, //up
- { 2,-1},{ 2,1}, //right
- { -1,2},{ 1,2} //down
- };
- //startingfrom (0,0)
- //int posX = 0;
- //int posY = 0;
- //starting from random position - from console
- int posX = int.Parse(Console.ReadLine());
- int posY = int.Parse(Console.ReadLine());
- int numMoves = 1;
- table[posX, posY] = numMoves;
- GoThroughTable(table, moves, posX, posY, numMoves);
- }
- private static void GoThroughTable(int[,] table, int[,] moves, int posX, int posY, int numMoves)
- {
- int tableSize = table.GetLength(0) * table.GetLength(1);
- if (numMoves == tableSize)
- {
- outputTable(table);
- return;
- }
- for (int i = 0; i < moves.GetLength(0); i++)
- {
- int newX = posX + moves[i, 0];
- int newY = posY + moves[i, 1];
- if (ValidMove(newX, newY, table))
- {
- numMoves++;
- table[newX, newY] = numMoves;
- GoThroughTable(table, moves, newX, newY, numMoves);
- numMoves--;
- table[newX, newY] = 0;
- }
- }
- }
- private static bool ValidMove(int newX, int newY, int[,] table)
- {
- return newX >= 0 && newY >= 0 && newX < table.GetLength(0) && newY < table.GetLength(0) && table[newX, newY] == 0;
- }
- private static void outputTable(int[,] matrix)
- {
- for (int i = 0; i <= matrix.GetLength(0) - 1; i++)
- {
- for (int j = 0; j <= matrix.GetLength(1) - 1; j++)
- {
- Console.Write($" {matrix[i, j],2}");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement