请原谅我的语法错误。
我会尽量解释我的问题是什么。
我正在做一个二维数组,从数组的一个点开始,我应该打印两个水平的,垂直的和斜的附近的单元格。

黄色细胞是起点,红色和灰色细胞是我要打印的细胞。
我发现的解决方案是制作4种不同的算法:1种打印水平细胞,另一种打印垂直细胞,另一种打印斜细胞(从右到左),另一种打印斜细胞(从左到右)。
所以我正在解决这个问题,就像我在处理向量一样,我认为这是一个非常糟糕的解决方案。
水平打印的例子:
int startPos=0;
int counter=5; //Five and not four, because it includes the start point that hasn't to be printed
if(column >= 2) startPos = column - 2;
else counter -= (2-column);
for(i=0; i<counter; i++){
if(startPos + i != column){ //the start point hasn't to be printed
printf("m-array[%d][%d] ", row, startPos + i);
}
}我从起点返回两个,然后打印下四个单元格。
发布于 2017-09-08 12:15:14
如果您希望4种“不同”算法为1,则只需找到它们之间共享的逻辑,并创建一个实现该逻辑的函数。
共享的部分是他们都打印了一行。每一行从不同的地方开始,以不同的方向打印。我称这个函数为printLine。
注意,我创建的函数可以用于静态和动态分配的数组。
您可以以不同的方式实现它。具体来说,您可以组合这两个for循环并添加一个测试,以防止主单元格被打印出来。
#include <stdio.h>
int isInBounds(int rows, int cols, int y, int x) {
return (y >= 0) && (y < rows) && (x >= 0) && (x < cols);
}
void printLine(int *array, // pointer to start of the array
int rows, int cols, // amount of rows and columns
int count, // how many steps before and after the given cell
int posY, int posX, // the position of the cell to print around
int dirY, int dirX) { // the direction to advance each time
int y = posY - count * dirY;
int x = posX - count * dirX;
int i = 0;
// loop till we get to the given cell
// increase y and x according to dirY and dirX
for(i = 0; i < count; i++, y += dirY, x += dirX) {
if(isInBounds(rows, cols, y, x)) {
// don't print if this cell doesn't exist
printf("Array[%d][%d] = %d\n", y, x, array[y * cols + x]);
}
}
y = posY + dirY;
x = posX + dirX;
// loop count times, starting 1 step after the given cell
for(i = 0; i < count; i++, y += dirY, x += dirX) {
if(isInBounds(rows, cols, y, x)) {
// don't print if this cell doesn't exist
printf("Array[%d][%d] = %d\n", y, x, array[y * cols + x]);
}
}
}
void main(void) {
int rows = 5;
int cols = 8;
int array[rows][cols]; // array is uninitialized
int count = 2; // you wanted to print 5 without middle, which means 2 from each side
int posY = 2;
int posX = 3;
/*************************
* initialize array here */
int i = 0;
for(; i < rows * cols; i++) {
*(((int *)array) + i) = i;
}
/************************/
printLine((int *)array, rows, cols,
count,
posY, posX,
1, 0); // move 1 row down
printLine((int *)array, rows, cols,
count,
posY, posX,
0, 1); // move 1 column to the right
printLine((int *)array, rows, cols,
count,
posY, posX,
1, 1); // move 1 row and column, so down and right
printLine((int *)array, rows, cols,
count,
posY, posX,
-1, 1); // same as last diagonal but now up and right
}https://stackoverflow.com/questions/46112842
复制相似问题