2

如果我有这个包含两个非零数据群的二维数组,我如何在两个单独的向量中传输非零值的所有索引。一个用于左侧的所有非零值的索引,一个用于右侧的所有非零值的索引?

{1,0,0,0,1,0} 
{1,1,0,0,1,1}
{1,0,0,0,0,0}

这是我到目前为止所做的:

我使用了for-loop,但我觉得它不正确:

for(int i=0;i<width;i++){
for(int j=0; j < height; j++){
if(Maps[i][j] > 0 || Maps[i+1][j] > 0 || Maps[i-1][j] > 0 || Maps[i][j+1] > 0 || Maps[i][j-1] > 0){ 
     row = j / width;
     col = j % width;
    }
}

我尝试使用 switch-case 但我没有继续使用它,因为它看起来很垃圾!

for(int i=0 ; i<width; i++){
   for(int j=0 ; j<height; j++){ 

      switch(){
          case (Maps[i][j] > 0):
             row = j / width;
         col = j % width;
         PIndAmp.push_back(std::make_pair(row,col));  
             break; 
          case (Maps[i][j] > 0 && Maps[i][j+1] > 0):
                   for(Maps[i][j] > 0){
                       row = j / width;
                       col = j % width;
                       PIndAmp.push_back(std::make_pair(row,col));
                     }
                   for(Maps[i][j+1] > 0){
                       row = j+1 / width;
                       col = j % width;
                       PIndAmp.push_back(std::make_pair(row,col));
                     }
                                     break; 

    }
}

提前致谢...

4

2 回答 2

0

这是广度优先搜索(或)深度优先搜索的经典应用。

确切的问题是在图中查找连接的组件

于 2013-10-18T09:25:11.423 回答
0

怎么样:

#include <iostream>
#include <string>
#include <vector>
#include <utility>

template<typename F, typename S>
std::ostream& operator<<(std::ostream& os, const std::pair<F, S>& t) {
    return os << '(' << t.first << ',' << t.second << ')';
}

template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
    for (auto& el : vec) {
        os << el << ' ';
    }
    return os;
}

int main()
{
    constexpr unsigned int width = 6;
    constexpr unsigned int height = 3;
    const unsigned int array[height][width] = {
        {1,0,0,0,1,0},
        {1,1,0,0,1,1},
        {1,0,0,0,0,0},
    };
    typedef std::vector<std::pair<unsigned int, unsigned int>> colonies;
    colonies left;
    colonies right;
    for (unsigned int y = 0; y < height; ++y) {
        colonies * vector = &left;
        for (unsigned int x = 0; x < width; ++x) {
            const unsigned int value = array[y][x];
            if (value == 0) {
                vector = &right;
            } else {
                vector->push_back(std::make_pair(y, x));
            }
        }
    }
    std::cout << "Right: " << std::endl << right << std::endl;
    std::cout << "Left: " << std::endl << left << std::endl;
}

输出:

+ g++-4.8 -std=c++11 -O2 -Wall -pedantic -pthread main.cpp
+ ./a.out
Right: 
(0,4) (1,4) (1,5) 
Left: 
(0,0) (1,0) (1,1) (2,0)

你可以在这里在线运行

于 2013-10-18T09:07:04.747 回答