search

Home  >  Q&A  >  body text

c++ - 无数个九宫格组成的矩阵,随机选一个点为中心,计算出它周围的8个格子内最大且比它大的格子做下一个中心,有什么简洁优美的计算方法吗?

PHP中文网PHP中文网2803 days ago936

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 13:30:23

    用一个二维数组保存每个格子上的数 这样格子a[i][j]上面的数(如果上面有数,不是边界)就是a[i-1][j], 左上角的数是a[i-1][j-1] 右上角的数是a[i-1][j+1],下一步怎么走的话就是拿这周围的几个数中最大的那个跟自己比较, 直到没有比他小的,用数组记录路径。

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:30:23

    If you are searching grid by grid, it is easiest to use a large two-dimensional array, and just write the eight surrounding grids by hand

    [x-1,y-1]
    [x,y-1]
    [x+1,y-1]
    ...
    [x+1,y+1]
    

    Very elegant.

    If the data set is large and regular, you can consider optimization methods to skip some grids to speed up the search. Of course, that’s another topic

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:30:23

    The vectors in eight directions can be listed in advance, thus avoiding writing eight repeated sections of code.

    As shown below:

    const int dx[] = {0, 0, 1, -1, -1, -1, 1, 1};
    const int dy[] = {1, -1, 0, 0, -1, 1, 1, -1};
    // ...
    for (int i = 0; i < 8; ++i) {
        int cur_x = x + dx[i];
        int cur_y = y + dy[i];
        // ...
    }

    reply
    0
  • Cancelreply