棋盘覆盖问题(C实现)——分治算法的思想

算法思想参考
https://www.cnblogs.com/Jason-Damon/archive/2013/06/14/3136893.html
https://wenku.baidu.com/view/e331f06c336c1eb91a375d75.html

C语言代码实现

#include

int matrix[100][100]={0};
int t=0;

void chessboard(int tr,int tc,int dr,int dc,int size);

int main(){
    int size;
    int tr=0,tc=0,dr,dc;
    int i,j;
    scanf("%d",&size);
    scanf("%d %d",&dr,&dc);
    chessboard(0,0,dr,dc,size);
    for(i=0;ifor(j=0;jprintf("%2d ",matrix[i][j]);
        }
        printf("\n");
    }
    return 0;
}

void chessboard(int tr,int tc,int dr,int dc,int size){
    if(size==1)return;
    int s=size/2;
    int cnt;
    cnt=t+1;
    t++;    
    //特殊方格在左上部分 
    if(dr<tr+s&&dcs){
        chessboard(tr,tc,dr,dc,s);
    }
    else {
        matrix[tr+s-1][tc+s-1]=cnt;
        chessboard(tr,tc,tr+s-1,tc+s-1,s);
    }
    //特殊方格在右上部分 
    if(dr<tr+s&&dc>=tc+s){
        chessboard(tr,tc+s,dr,dc,s);
    }
    else {
        matrix[tr+s-1][tc+s]=cnt;
        chessboard(tr,tc+s,tr+s-1,tc+s,s);
    }
    //特殊方格在左下部分 
    if(dr>=tr+s&&dcs){
        chessboard(tr+s,tc,dr,dc,s);
    }
    else {
        matrix[tr+s][tc+s-1]=cnt;
        chessboard(tr+s,tc,tr+s,tc+s-1,s);
    }
    //特殊方格在右下部分
    if(dr>=tr+s&&dc>=tc+s){
        chessboard(tr+s,tc+s,dr,dc,s);
    }
    else {
        matrix[tr+s][tc+s]=cnt;
        chessboard(tr+s,tc+s,tr+s,tc+s,s);
    } 
}

你可能感兴趣的:(C)