Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 06.03.2017, 19:15   #1
marymap
Новичок
Джуниор
 
Регистрация: 06.03.2017
Сообщений: 1
По умолчанию рекурсия

На шахматной доске определить поля, в которые может попасть конь за n ходов из указанной позиции.Размер шахматной доски также вводится.

вот программа,вроде логична, так долго над ней билась.
помогите! что не так! лабу завтра сдавать уже!


Код:
#include <iostream>
#include <math.h>  

using namespace std; 

int ** func(int ** chess_board, int horse_pos_x, int horse_pos_y, int razm, int key) 
{ 
key++; 
if((horse_pos_y+2<razm)&&(horse_pos_x+1<razm)) 
{ 
chess_board[horse_pos_y + 2][horse_pos_x + 1] = key; 
func(chess_board,horse_pos_x+1, horse_pos_y+2, razm, key); 
} 
if ((horse_pos_y + 1<razm) && (horse_pos_x + 2<razm)) 
{ 
chess_board[horse_pos_y + 1][horse_pos_x + 2] = key; 
func(chess_board, horse_pos_x+2, horse_pos_y+1, razm, key); 
} 
if ((horse_pos_y -1 <razm)&&(horse_pos_y - 1 >=0)&& (horse_pos_x + 2<razm)) 
{ 
chess_board[horse_pos_y - 1][horse_pos_x + 2] = key; 
func(chess_board, horse_pos_x+2, horse_pos_y-1, razm, key); 
} 
if ((horse_pos_y - 2 <razm) && (horse_pos_y - 2 >= 0) && (horse_pos_x + 1<razm)) 
{ 
chess_board[horse_pos_y - 2][horse_pos_x + 1] = key; 
func(chess_board, horse_pos_x+1, horse_pos_y-2, razm, key); 
} 
if ((horse_pos_y - 2 <razm) && (horse_pos_y - 2 >= 0) && (horse_pos_x - 1<razm)) 
{ 
chess_board[horse_pos_y - 2][horse_pos_x -1 ] = key; 
func(chess_board, horse_pos_x-1, horse_pos_y-2, razm, key); 
} 
if ((horse_pos_y - 1 <razm) && (horse_pos_y - 1 >= 0) && (horse_pos_x -2 <razm)) 
{ 
chess_board[horse_pos_y - 1][horse_pos_x -2] = key; 
func(chess_board, horse_pos_x-2, horse_pos_y-1, razm, key); 
} 
if ((horse_pos_y +1 <razm) && (horse_pos_x - 2 >= 0) && (horse_pos_x -2<razm)) 
{ 
chess_board[horse_pos_y + 1][horse_pos_x - 2] = key; 
func(chess_board, horse_pos_x-2, horse_pos_y+1, razm, key); 
} 
if ((horse_pos_y +2 <razm) && (horse_pos_x-1 >= 0) && (horse_pos_x - 1<razm)) 
{ 
chess_board[horse_pos_y +2][horse_pos_x - 1] = key; 
func(chess_board, horse_pos_x-1, horse_pos_y+2, razm, key); 
} 
return chess_board; 
} 

int main() 
{ 
int n,k=0,horse_pos_x,horse_pos_y,fl; 

cout << "RAZM:" << endl; 
cin >> n; 
int **chess_board = new int*[n]; 
for (int i = 0;i < n;i++) 
chess_board[i] = new int[n]; 
for (int i = 0;i < n;i++){ 
for (int j = 0;j < n;j++) 
chess_board[i][j] = 0; }
cout<< "HORSE:"<< endl; 
cin >> horse_pos_x >> horse_pos_y; 
cout << "KOL:" << endl; 
cin >> fl; 
chess_board[horse_pos_y][horse_pos_x] = -1; 
func(chess_board, horse_pos_x, horse_pos_y, n, k); 
for (int i = 0;i < n;i++) {
for (int j = 0;j < n;j++) {
//if (chess_board[i][j] == fl)
//cout << "x" << j << " " << "y" << i<<endl; 
cout<<chess_board[i][j]<<" ";}}
system("pause"); 
return 0; 
}
marymap вне форума Ответить с цитированием
Старый 06.03.2017, 23:28   #2
New man
Форумчанин
 
Регистрация: 24.01.2011
Сообщений: 774
По умолчанию

У тебя спагетти-код, так что исправлять я его не буду, но могу просто дать своё предложение.

Держи.
Внимательно прочитай код.
Я разбил код на осмысленные функции, сделал некоторые вещи более логично. Что непонятно, спрашивай.
Код:
#include <iostream>
#include <math.h>





// Подсчитывает новое положение, прибавляя соответствующее значение хода к начальной позиции
std::pair<int,int> get_new_pos(const std::pair<int, int>& current_position,int step_index)
{
    // Выносим все возможные ходы фигуры
    static constexpr  std::pair<int,int> avaible_steps[] = {
        std::make_pair(-1,2),
        std::make_pair(-1,-2),
        std::make_pair(1,2),
        std::make_pair(1,-2),
        std::make_pair(2,1),
        std::make_pair(-2,1),
        std::make_pair(2,-1),
        std::make_pair(-2,-1)
        }; 
    return std::make_pair(current_position.first+avaible_steps[step_index].first,
                              current_position.second+avaible_steps[step_index].second );
}

bool is_position_correct(int razm, const std::pair<int,int>& pos)
{
    return pos.first>=0 && pos.second >=0 && pos.first<razm && pos.second<razm;
}

// Не нужно возвращать значение функции, так как вы меняете только состояние доски, а доска у тебя одна
// Заменил две переменных для позиции одной парой, так как это компактнее и логичнее, т.к. они одно целое по своему предназначению
// pos.first - индекс строки; pos.second - индекс столбца
void func(int** chess_board, const std::pair<int,int>& last_pos, int razm, int key)
{
    // Условие выхода из рекурсии
    if(key==0)
    {
        chess_board[last_pos.first][last_pos.second] = 1;
        return;
    }
    // Количество возможных ходов
    static const int AVAIBLE_STEPS_COUNT = 8;
    // А теперь их перебираем
    for(int i = 0; i<AVAIBLE_STEPS_COUNT; ++i)
    {
        std::pair<int, int> new_pos = get_new_pos(last_pos, i);
        // Если новая позиция корректная
        if(is_position_correct(razm,new_pos))
        {
            // То делаем рекурсивный вызов
            func(chess_board, new_pos, razm, key-1);
        }
    }
}

int main()
{
    using namespace std;
    int n, fl;
    pair<int,int> initial_horse_position;
    cout << "RAZM:" << endl;
    cin >> n;
    int** chess_board = new int*[n];
    for (int i = 0; i < n; i++)
        chess_board[i] = new int[n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            chess_board[i][j] = 0;
    }
    cout << "HORSE:" << endl;
    cin >> initial_horse_position.first
        >> initial_horse_position.second;
    // Декрементируем каждый индекс, так как обыватель считает с 1, а мы с 0
    initial_horse_position.first--;
    initial_horse_position.second--;
    
    cout << "KOL:" << endl;
    cin >> fl;
    
    // Он же не факт, что будет на этой клетке в конце всех ходов
    //chess_board[horse_pos_y][horse_pos_x] = -1;
    
    // Проверяем ввод
    if(!is_position_correct(n,initial_horse_position))
    {
        cout<<"You make the biggest error in your live, kholop!"<<endl;
        system("pause");
        // Возвращаем ошибку
        return -1;
    }
    func(chess_board, initial_horse_position, n, fl);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            //if (chess_board[i][j] == fl)
            //cout << "x" << j << " " << "y" << i<<endl;
            cout << chess_board[i][j] << " ";
        }
        cout<<endl;
    }
    system("pause");
    return 0;
}
a.k.a. Angelicos Phosphoros
Мой сайт

Последний раз редактировалось New man; 07.03.2017 в 00:08.
New man вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Рекурсия c++ sv011 Помощь студентам 0 03.12.2012 23:35
Рекурсия gafruslan Помощь студентам 1 21.12.2010 17:43
Рекурсия <Tyz> Паскаль, Turbo Pascal, PascalABC.NET 3 18.12.2010 23:22
Рекурсия. KOPC1886 Помощь студентам 1 09.12.2010 21:37
Рекурсия на С++ Nitriyc Помощь студентам 0 29.04.2010 07:29