栈的运用(4)

问题描述:

  设以二维数组g(1...m, 1....n)表示一个图像区域,g[i, j]表示该区域中点(i, j)所具颜色,其值为从0k的整数。编写算法置换点(i0, j0)所在区域的颜色。约定和(i0, j0)同色的上,下,左,右的邻结点为同色区域的点。 

问题分析:

 g[i,j]表示该区域中点(i,j)所具颜色,它本身代表的是一个点,它的值代表它的颜色,要置换(i0, j0)所在区域的点,也就是说要改变(i0,j0)的值

算法:

Void Change(int  i0,  int  j0)

{

int  i;

Int  g[m,n];

G[i0,j0]=k;

G[i0+1,j0]=k;

G[i0,j0+1]=k;

G[i0-1,j0]=k;

G[i0,j0-1]=k; 

}

//简单的理解,就是你要改变的k值传进来,把原来的k0值替换是不?

//想得不深,以至于没有思路了

书上的算法:

#include<stdio.h>

#include<stdlib.h>

Typedef  struct{

Int x;

Int y;

}PostType //表示位置的结构体

 

Typedef  struct{

Int color;

Int visited;

PostType seat;

}ElemType;

 

#define M 8

#define N 8

 

ElemType  g[M][N];

 

Void CreateGDS(ElemType  g[M][N]);

Void ShowGraphArray(ElemType  g[M][N]);

Void RegionFilling(ElemType  g[M][N],  PostType  CurPos,  int  NewColor);

 

Int main()

{

CreateGDS(g);

ShowGraphArray(g);

 

PostType  StartPos;

StartPos.x=5;

StartPos.y=5;

Int  FillColor=6;

RegionFilling(g  StartPos, FillColor);

ShowGraphArray(g);

Return 0;

}

Void RegionFilling(ElemType  g[M][N],  PostType  CurPos,  int  NewColor)

{

   Stack s;

InitStack(s);

ElemType e;

Int OldColor=g[CurPos.x][CurPos.y].color;

Push(s,g[CurPos.x][CurPos.y]);

While(!StackEmpty(s)){

Pop(s);

CurPos=s.seat;

G[CurPos.x][CurPos.y].color=fillcolor;

G[CurPos.x][CurPos.y].visited=1;

  

If(CurPos.x<M&&!G[CurPos.x+1][CurPos.y].visited&&G[CurPos.x+1][CurPos.y].color==

oldcolor)

 Push(s,G[CurPos.x+1][CurPos.y]);

 

If(CurPos.x>0&&!G[CurPos.x-1][CurPos.y].visited&&G[CurPos.x-1][CurPos.y].color==

oldcolor)

 Push(s,G[CurPos.x-1][CurPos.y]);

 

If(CurPos.x<M&&!G[CurPos.x][CurPos.y+1].visited&&G[CurPos.x][CurPos.y+1].color==

oldcolor)

 Push(s,G[CurPos.x][CurPos.y+1]);

 

If(CurPos.x<M&&!G[CurPos.x][CurPos.y-1].visited&&G[CurPos.x][CurPos.y-1].color==

oldcolor)

 Push(s,G[CurPos.x][CurPos.y-1]);

}

}

Void CreateGDS(ElemType  g[M][N])

{

   Int  i,j;

   For(int i=0;i<M;i++)

     For(int j=0;j<N;j++)

      {

        G[i][j].seat.x=i;

        G[i][j].seat.y=j;

        G[i][j].visited=0;

        G[i][j].color=0;

       }

     书上写的给它们的颜色赋值是这样写的

     For(i=2;i<5;i++)

       For(j=2;j<4;j++)

         G[i][j].color=3;

     For(i=5;i<M-1;i++)

       For(j=3;j<6;j++)

        G[i][j].color=3;

 我的想法是如果数组的大小是8的话 那么(4,4)是中点,将它的颜色赋值为3的话

 它的上下左右的点都为3

 G[4][4]=3;

 G[5][4]=3;

 G[3][4]=3;

 G[4][3]=3;

 G[4][5]=3;

}

Void  ShowGraphArray(ElemType  g[M][N])

{

Int i,j;

For(i=0;i<M;i++){

   For(j=0;j<N;j++)

     Printf(%d,g[i][j].color);

}

}

posted @ 2013-04-26 14:12  wj704  阅读(167)  评论(0编辑  收藏  举报