20×20的棋盘,用0~9十个数字随意填充,随意选择其中一个方格,查找与其相邻的填充同样数字的所有方格,如果棋盘更大,用什么算法比较好?我只知道递归,不知道还有没有效率更高的算法?如果有代码提供参考更好,谢谢!

解决方案 »

  1.   

    用递归应该很简便
    给你一个区域生长算法思路
    这个算法是在一个数组里根据一个生长点寻找与之相邻的所有非零象素点row_count , col_count 数组大小
    void CCloud::ExpandPixel(int xPos, int yPos , unsigned char imageArray[][COL_COUNT])
    {
    //parameters Check
    PixelPos nPixelPos = GetPixelPos( xPos , yPos ); if ( nPixelPos == NONE_OF_UP )
    {
    return ;
    } gl_ImageBuffer[xPos][yPos] = 1 ; //1,2,3,4,5,6,7,8八邻域八个递归操作
    //gl_ImageBuffer是对imageArray的一份拷贝
    if( ((nPixelPos>=3 && nPixelPos <=5 ) || nPixelPos ==8 ) &&
     imageArray[xPos-1][yPos-1]!=0 &&
     gl_ImageBuffer[xPos-1][yPos-1]!=1 )
    {
    ExpandPixel( xPos-1 , yPos-1 ,imageArray) ;
    } if( nPixelPos>=3 && nPixelPos<=8 && 
    imageArray[xPos][yPos-1]!=0 &&
    gl_ImageBuffer[xPos][yPos-1]!=1 )
    {
    ExpandPixel ( xPos , yPos-1 , imageArray) ;
    } if( nPixelPos>=5 && nPixelPos<=8 &&
    imageArray[xPos+1][yPos-1]!=0 &&
    gl_ImageBuffer[xPos+1][yPos-1]!=1 )
    {
    ExpandPixel( xPos+1 , yPos-1 , imageArray ) ;
    } if( ((nPixelPos>=0 && nPixelPos<=1) ||
    (nPixelPos>=5 && nPixelPos<=8)) &&
    imageArray[xPos+1][yPos]!=0 &&
    gl_ImageBuffer[xPos+1][yPos] !=1 )
    {
    ExpandPixel( xPos+1 , yPos , imageArray ) ;
    } if( ((nPixelPos>=0 && nPixelPos<=1) ||
    (nPixelPos>=7 && nPixelPos<=8)) &&
    imageArray[xPos+1][yPos+1]!=0 &&
    gl_ImageBuffer[xPos+1][yPos+1]!=1 )
    {
    ExpandPixel( xPos+1 , yPos+1 , imageArray) ;
    } if( ((nPixelPos>=0 && nPixelPos<=3) ||
    (nPixelPos>=7 && nPixelPos<=8)) &&
    imageArray[xPos][yPos+1]!=0 &&
    gl_ImageBuffer[xPos][yPos+1]!=1 )
    {
    ExpandPixel( xPos , yPos+1 ,imageArray ) ;
    } if( ((nPixelPos>=1 && nPixelPos<=3) ||
    nPixelPos==8) &&
    imageArray[xPos-1][yPos+1] !=0 &&
    gl_ImageBuffer[xPos-1][yPos+1]!=1 )
    {
    ExpandPixel( xPos-1 , yPos+1,imageArray ) ;
    } if( ((nPixelPos>=1 && nPixelPos<=5 ) ||
    nPixelPos==8) &&
    imageArray[xPos-1][yPos] !=0 &&
    gl_ImageBuffer[xPos-1][yPos] !=1 )
    {
    ExpandPixel( xPos-1 , yPos,imageArray ) ;
    }
    }PixelPos CCloud::GetPixelPos(int xPos, int yPos)
    {
    //parameter check 
    if( xPos<0 || yPos<0 || xPos>=ROW_COUNT || yPos>=COL_COUNT )
    {
    return NONE_OF_UP ;
    } if( xPos ==0 && yPos ==0 )
    return UP_LEFT ; if( yPos ==0 && xPos== ROW_COUNT-1 )
    return UP_RIGHT ; if( xPos ==0 && yPos == COL_COUNT-1 )
    return DOWN_LEFT ; if ( xPos ==ROW_COUNT-1 && yPos == COL_COUNT-1 )
    return DOWN_RIGHT ; if( xPos ==0 )
    return LEFT ; if ( xPos == ROW_COUNT-1 )
    return RIGHT ; if( yPos == 0 )
    return UP ; if( yPos == COL_COUNT-1 )
    return DOWN ; return CENTER ;
    }
      

  2.   

    enum PixelPos { UP_LEFT , UP , UP_RIGHT ,
                   RIGHT , DOWN_RIGHT , DOWN,
       DOWN_LEFT , LEFT , CENTER , NONE_OF_UP };