我试图找出二维数组中的行程编码。我随机填充了我的尺寸x尺寸的板,0和1。然后我的程序运行曲折行走(起始位置=右上角)以读取该模式中的0和1。这对我有用,如下所示。但是,我需要帮助读取连续的0或1并计算它们每次出现的次数。这是一个例子:
/* n = 4 (i.e. 4 x 4 board)
1010
1010
0001
1000
Run-length coding on the zigzag path:
(0,2)
(1,1)
(0,1)
(1,2)
(0,3)
(1,2)
(0,4)
(1,1) */
这是我到目前为止所拥有的。
void runLengthCoding()
{
int flag = 1; // alternate between one and negative one depending on direction.
//2*maxsize-1 is the number of segments.
for(int i = 2 * maxSize - 1; i >= 0; i--) //outer for loop goes through the segments. #of segments
{
//determine the starting element.
int r, c;
if (flag == -1)// if(i%2==1)
{
if(i > maxSize)
r = i - maxSize - 1;
else
r = maxSize - 1;
}
else
{
if(i >= maxSize)
r = 0;
else
r = maxSize - i;
}
c = i - maxSize + r;
while(r >=0 && r <= maxSize -1 && c >= 0 && c <= maxSize - 1)
{
System.out.print(A[r][c] + " ");
int cnt = 0;
if (A[r][c] == 0)
if(flag == 1)
{
r++;
c++;
}
else
{
r--;
c--;
}
}
//change the moving direction
flag = -flag;
System.out.println();
}
}
// print the run-length coding result, i.e., content of rlc[][]
void printCodingResult()
{
System.out.println("Run-length coding on the zigzag path: ");
}
为了执行rlc [] [],我想每次A [r] [c]从0变为1或反之,记录并重置计数。但是我该如何融入呢。 rlc [] []将如何记住这一点?从示例中可以看出,rlc [] []以两列的格式显示(一个用于0或1,第二个用于计数)。欣赏任何想法。感谢。
答案 0 :(得分:0)
void runLengthCoding()
{
int flag = -1;// 1: up -1: down
System.out.println("runLengthCoding: ");
for (int i=0; i<=(maxSize-1)*2; i++)//i=pass variable
{
int r, c, t;
if (flag == 1)
{
c = Math.min(maxSize-1, (2*(maxSize-1))-i);
t=(maxSize-1)-c;
r = i-t;
}
else
{
r = Math.max(0, i-(maxSize-1));
t=i-r;
c = (maxSize-1)-t;
}
while (r >=0 && c >=0 && r < maxSize && c < maxSize)
{
System.out.print(A[r][c] + " ");
r -= flag;
c -= flag;
}
flag = -flag;//changes flag in order to change direction of scan
System.out.println();
}
}