如何解决随机行走问题中的这段代码?[关闭]

问题描述 投票:0回答:1

enter image description here

#include<iostream>   
#include<ctime>
#include<cstdlib>
using namespace std;

int main() {
     int arr[5][5] = { 0 };
int x =0, y = 0;
int mx,my;
int cnt = 0;
srand(time(NULL));
while(1) {
    bool a = true;
    int i = rand() % 8;
    if (i == 0) {
        mx = -1, my = 0;
        if ((x + mx) > 4 || (x + mx) < 0 || (y + my) > 4 || (y + my) < 0) continue;
        arr[x + mx][y + my] ++;
        x += mx;
        y += my;
        cnt++;
        }
    if (i == 1) {
        mx = 1, my = -1;
        if ((x + mx) > 4 || (x + mx) < 0 || (y + my) > 4 || (y + my) < 0) continue;
        arr[x + mx][y + my]++;
        x += mx;
        y += my;
        cnt++;
     }
     if (i == 2) {
        mx = 0, my = -1;



        if ((x + mx) > 4 || (x + mx) < 0 || (y + my) > 4 || (y + my) < 0) continue;
        arr[x + mx][y + my] ++;
        x += mx;
        y += my;
        cnt++;
        }
    if (i == 3) {
        mx = 1, my = 1;
        if ((x + mx) > 4 || (x + mx) < 0 || (y + my) > 4 || (y + my) < 0) continue;
        arr[x + mx][y + my] ++;
        x += mx;
        y += my;
        cnt++;
        }
    if (i == 4) {
        mx = 1, my = 0;
        if ((x + mx) > 4 || (x + mx) < 0 || (y + my) > 4 || (y + my) < 0) continue;
        arr[x + mx][y + my] ++;
        x += mx;
        y += my;
        cnt++;
        }
    if (i == 5) {
        mx = 1, my = -1;
        if ((x + mx) > 4 || (x + mx) < 0 || (y + my) > 4 || (y + my) < 0) continue;
        arr[x + mx][y + my] ++;
        x += mx;
        y += my;
        cnt++;
        }
    if (i == 6) {
        mx = 0, my = -1;
        if ((x + mx) > 4 || (x + mx) < 0 || (y + my) > 4 || (y + my) < 0) continue;
        arr[x + mx][y + my] ++;
        x += mx;
        y += my;
        cnt++;
    }
    if (i == 7) {
        mx = -1, my = -1;
        if ((x + mx) > 4 || (x + mx) < 0 || (y + my) > 4 || (y + my) < 0) continue;
        arr[x + mx][y + my]++;
        x += mx;
        y += my;
        cnt++;
    }
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            if (arr[i][j] == 0) a = false;
        }
    }
    if (a == true)break;
}
cout << cnt;
return 0;
}

我在解决一个随机行走的算法问题,但是不知道哪里出了问题.编译的时候,黑屏上什么都不显示。不使用函数而加长了,但我认为没有什么问题.如果有什么地方会导致错误,请解释thanks for reading this post I'm waiting your answer.

c++ algorithm loops
1个回答
2
投票

问题在于,你的各种 if 不要探索所有可能的动作,你可以做给你在一个位置x,y。例如,如果你看到你做什么在 i == 2

if (i == 2) {
    mx = 0, my = -1;

或者 i == 6

if (i == 6) {
    mx = 0, my = -1;

你也是这样做的。特别是:你看这个。

- - V
V X V
V V V

你错过了向上和向上向左的两个动作。

我会回顾各种if运动(你保存在这两个变量中,mx和my的)。

作为对你代码的改进,我会在你真正能做的动作之间选择一个随机的动作......这样会更干净。

© www.soinside.com 2019 - 2024. All rights reserved.