有一面用数字建造的墙。 0
表示有一个洞,块不能坐在洞上。有人用一把特殊的枪,用一次射击的方式射击所有积木
所以我有一个叫做墙的矩阵,不得不写一把枪。我写了这个程序,但我有一个问题,我不明白为什么会这样。在我的代码中
#include <iostream>
#include <cstdio>
using namespace std;
int createWall( int &height, int &length, int wall[][ 100 ], int shots )
{
int i;
int j;
cin >> height;
cin >> length;
cin >> shots;
for ( i = 0; i < height; i++ )
{
for ( j = 0; j < length; j++ )
{
cin >> wall[ i ][ j ];
}
}
return shots;
}
void wallNow( int height, int length, int wall[][ 100 ] )
{
int i;
int j;
for ( i = 0; i < height; i++ )
{
for ( j = 0; j < length; j++ )
{
cout << wall[ i ][ j ] << " ";
}
cout << "\n";
}
}
void destroyWall( int height, int length, int wall[][100], int shots )
{
int i;
int j;
int k;
int x;
int aimedBlocks;//number to be "destroyed"
//set all aimedBlocks to 0
for ( x = 0; x < shots; x++ )
{
cin >> aimedBlocks;
for ( i = 0; i < height; i++ )
{
for ( k = 0; k < length; k++ )
{
if ( wall[ i ][ k ] == aimedBlocks )
{
wall[ i ][ k ] = 0;
}
}
}
}
int counter;//I use this variable because at some point I have a 0 followed only by 0's
for ( i = 0; i < length; i++ )
{
j = height - 1;
counter = 0;
//if I find a 0 then I move all elements higher that it one step down
while ( counter < height )
{
if ( wall[ j ][ i ] == 0 )
{
for ( k = j; k > 0; k-- )
{
wall[ k ][ i ] = wall[ k - 1 ][ i ];
}
wall[ height - j - 1 ][ i ] = 0;
}
else
j--;//I don't always go up ene step because the "block" droped in place of 0 may be 0
counter++;
}
}
}
int main()
{
int height;
int length;
int wall[ 100 ][ 100 ];
int shots = 0;
shots = createWall( height, length, wall, shots );
destroyWall( height, length, wall, shots );
wallNow( height, length, wall );
}
我真的不明白为什么行wall[ height - j - 1 ][ i ] = 0;
适用于以下示例中的前4列,但它不适用于最后一列。
格式输入:
height length shots
wall_0_0 ... wall_0_length
... ... ...
wall_height ... wall_height_length
shot_0 ... shot_shots
输入:
4 5 3
3 5 4 5 1
2 1 1 5 3
1 1 5 5 1
5 5 1 4 3
1 5 1
删除与1
,5
,1
匹配的所有值。墙壁遗骸必须落到底部。
输出:
0 0 0 0 0
0 0 0 0 0
3 0 0 0 0
2 0 4 4 3
预期:
0 0 0 0 0
0 0 0 0 0
3 0 0 0 3
2 0 4 4 3
请帮我解决这个问题。我找不到它调试代码。
答案 0 :(得分:2)
你的算法很奇怪,我不明白你想做什么。
实现目的的一种简单方法是从墙的左侧向右侧迭代,然后从底部到顶部迭代。每次获得0
时,您都会在顶部搜索非零值,并在找到它时进行交换。
示例(非常基本可以改进):
for (size_t i = 0; i < length; i++) { // i is for iterate from left(0) to right(length - 1)
size_t j = height; // j is for iterate from bot(height - 1) to top(0)
while (j-- > 0) {
if (wall[j][i] == 0) {
size_t k = j; // k is for found a non zero value from j - 1 to the top(0)
while (k-- > 0) {
if (wall[k][i] != 0) {
wall[j][i] = wall[k][i];
wall[k][i] = 0;
break;
}
}
}
}
}
注意:
size_t
,因为这是索引的类型。std::vector
并在C ++中使用iterator。