

1 #include<stdio.h> 2 typedef struct{ 3 int x,y; 4 int color; 5 }element; 6 typedef struct{ 7 element DArray[50][50];//二维数组本身不能存储其下标,故要用结构体记录其下标 8 int nrow,ncol; 9 }Big; 10 typedef struct{ 11 element array[50]; 12 int top; 13 }Stack; 14 void Inite(Stack*S) 15 { 16 S->top=-1; 17 } 18 element Pop(Stack*S) 19 { 20 element e; 21 e=S->array[S->top]; 22 S->top--; 23 return e; 24 } 25 void Push(Stack*S,element e) 26 { 27 S->top++; 28 S->array[S->top]=e; 29 } 30 int Empty(Stack*S) 31 { 32 if(S->top==-1)return 1; 33 else return 0; 34 } 35 void Create(Big*B) 36 { 37 scanf("%d %d",&B->nrow,&B->ncol); 38 for(int i=1;i<=B->nrow;i++) 39 for(int j=1;j<=B->ncol;j++) 40 { 41 scanf("%d",&B->DArray[i][j].color); 42 B->DArray[i][j].x=i; 43 B->DArray[i][j].y=j; 44 } 45 } 46 void Change(Big*B,int x,int y,int cor) 47 { 48 Stack T; 49 Inite(&T); 50 int initcor=B->DArray[x][y].color; 51 element e; 52 Push(&T,B->DArray[x][y]); 53 while(!Empty(&T)) 54 { 55 /*主*/ 56 e=Pop(&T);//出栈的过程其实就是实现一层递归的过程 57 e.color=cor; 58 B->DArray[e.x][e.y]=e;//别忘了赋值给原始内存 59 60 /*次*/ 61 if(e.x-1>=1&&B->DArray[e.x-1][e.y].color==initcor)Push(&T,B->DArray[e.x-1][e.y]); 62 if(e.x+1<=B->nrow&&B->DArray[e.x+1][e.y].color==initcor)Push(&T,B->DArray[e.x+1][e.y]); 63 if(e.y-1>=1&&B->DArray[e.x][e.y-1].color==initcor)Push(&T,B->DArray[e.x][e.y-1]); 64 if(e.y+1<=B->ncol&&B->DArray[e.x][e.y+1].color==initcor)Push(&T,B->DArray[e.x][e.y+1]); 65 } 66 } 67 void Order(Big*B) 68 { 69 for(int i=1;i<=B->nrow;i++) 70 { 71 for(int j=1;j<=B->ncol;j++) 72 { 73 printf("%d ",B->DArray[i][j].color); 74 } 75 printf("\n"); 76 } 77 78 } 79 int main() 80 { 81 Big B; 82 int x,y,cor; 83 Create(&B); 84 scanf("%d %d %d",&x,&y,&cor); 85 Change(&B,x,y,cor); 86 Order(&B); 87 return 0; 88 }
此题用意:用栈表示递归,其中修改颜色的操作即可放在入栈时也可放在出栈时,但出栈操作必伴随着将下一级(周围同颜色区域元素)入栈