動物一筆畫完

寫在前面,這個是我最近幫我學弟做的一個作業,2020年6月份左右。在這個時間段不要直接複製提交呀,這樣你們都會被認爲作弊的。
隨便找個c++的環境就可以跑這個程序。如果幫助到你,可以打賞杯咖啡嗎。

#include <iostream>
#include <string>
using namespace std;
#define row 10
#define col 10
int matrix[row][col];
bool vis[row][col];
int r, c;
int countOne = 0;
string res;
int startRow, startCol;
int dR[4] = {0, 1, -1, 0};
int dC[4] = {1, 0, 0, -1};
bool getRes = false;
void input()
{
    res.clear();
    countOne = 0;
    cout<<"輸入圖形的行數和列數"<<endl;
    cin >> r >> c;
    cout<<"輸入圖形(可以走標記爲1,不可走爲0,起始點爲1)"<<endl;
    for (int i = 0; i < r; i++)
    {
        for (int j = 0; j < c; j++)
        {
            cin >> matrix[i][j];
            if (matrix[i][j] == 1)
            {
                countOne = countOne + 1;
            }
            vis[i][j] = false;
        }
    }
    cout<<"輸入起始點座標(下標形式)"<<endl;
    cin >> startRow >> startCol;
}
void dfsAndTraceBack(int rIndex, int cIndex)
{
    for (int i = 0; i < 4; i++)
    {
        if ((res.size() + 1) == countOne)
        {
            getRes = true;
            return;
        }
        int tmpR = rIndex + dR[i];
        int tmpC = cIndex + dC[i];
        if (!(0 <= tmpR && tmpR < r))
        {
            continue;
        }
        if (!(0 <= tmpC && tmpC < c))
        {
            continue;
        }
        if (matrix[tmpR][tmpC] == 1 && vis[tmpR][tmpC] == false && !getRes)
        {
            switch (i)
            {
            case 0:
                res = res + "R";
                break;
            case 1:
                res = res + "D";
                break;
            case 2:
                res = res + "U";
                break;
            case 3:
                res = res + "L";
                break;
            default:
                break;
            }
            vis[tmpR][tmpC] = true;
            dfsAndTraceBack(tmpR, tmpC);
            if(!getRes)
            {
                vis[tmpR][tmpC] = false;
                res.pop_back();
            }
        }
    }
}
void solve()
{
    vis[startRow][startCol] = true;
    dfsAndTraceBack(startRow, startCol);
}
int main()
{
    input();
    solve();
    cout << res << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章