假设我有一个M * N数组,我必须遍历。有M * N个单元格(从1到M * N开始)。将有一个输入n并且根据我将不得不移动到下一个可能的单元格。 小区n的人只能在他的左,右或前小区穿越。我将不得不随机选择一个位置并显示它。
我的示例代码:
#include<stdio.h>
#include<math.h>
int main()
{
int row,col,n,p;
int array[3];
printf("\nEnter row and columns:");
scanf("%d""%d",&row,&col);
printf("\nEnter a position:");
scanf("%d",&n);
array[3]={n-1,n+1,n-row); //three possible movements(although I have used 1D array here,n determines the cell position(say: any value from 1 to 25), I have treated the array positions as 2D. For example: if n=7, then for a 5*5 array, possible movements are cells 6,8 and 2
p= array[ rand() % 3 ]+1; //choosing a next random position
printf("\nnext cell is %d",p);
}
但是有一个问题。让我们考虑一个5 * 5阵列的场景:
from cell 1, I can only move to right.
from cell 2,3,4, I can move to both left and right cells.
from cell 5, I can only move left.
from cell 6,11,16,21, I can move only right and upwards.
from cell 25,20,15,10, I can move at only left and upwards
现在对于上述单元格,上述程序可能会生成错误的位置(垃圾值如负数或大于25)。这只是一般情况或5 * 5阵列。但是我如何在任何M * N阵列中处理这种类型的条件。我可以在上述程序中应用任何规则来获得正确的输出吗?
答案 0 :(得分:0)
我建议您单独使用m
和n
解决问题,而不是使用m*n
来计算。{
如果电路板的大小为N*M
(N
行,M
列):
如果当前行为n (0<=n<=N-1)
且当前列为m (0<=m<=M-1)
:
if n==0 you can only move right.
else if n==N-1 you can only move left.
else both.
if m==0 you can only move down.
else if m==M-1 you can only move up.
else both.
通过这个你可以知道如何从数组[n] [m];
移动