C++程序源代碼如下: // 棋盤覆蓋.cpp : 定義控制台應用程序的入口點。 //
#include "stdafx.h" #include<iostream> #include<fstream> using namespace std; int tile=1; //L型骨牌的編號(遞增) int board[100][100]; //棋盤 /***************************************************** * 遞歸方式實現棋盤覆蓋算法 * 輸入參數: * tr:當前棋盤左上角的行號 * tc:當前棋盤左上角的列號 * dr:當前特殊方格所在的行號 * dc:當前特殊方格所在的列號 * size:size=2^k,棋盤規格為2^k*2^k *****************************************************/ void chessBoard ( int tr, int tc, int dr, int dc, int size ) { if ( size==1 ) //棋盤方格大小為1,說明遞歸到最里層 return; int t=tile++; //每次遞增1 int s=size/2; //棋盤中間的行、列號(相等的) //檢查特殊方塊是否在左上角子棋盤中 if ( dr<tr+s && dc<tc+s ) //在 chessBoard ( tr, tc, dr, dc, s ); else //不在,將該子棋盤右下角的方塊視為特殊方塊 { board[tr+s-1][tc+s-1]=t; 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 //不在,將該子棋盤左下角的方塊視為特殊方塊 { board[tr+s-1][tc+s]=t; chessBoard ( tr, tc+s, tr+s-1, tc+s, s ); } //檢查特殊方塊是否在左下角子棋盤中 if ( dr>=tr+s && dc<tc+s ) //在 chessBoard ( tr+s, tc, dr, dc, s ); else //不在,將該子棋盤右上角的方塊視為特殊方塊 { board[tr+s][tc+s-1]=t; 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 //不在,將該子棋盤左上角的方塊視為特殊方塊 { board[tr+s][tc+s]=t; chessBoard ( tr+s, tc+s, tr+s, tc+s, s ); } } int fuc(int i) { int count = 0; while(i) { count += i&0x01; i >>= 1; } if(count < 2) return 1; else return 0; }
void menu();
void input() { ofstream outfile; outfile.open("output.txt"); int size; int index_x,index_y; flag: cout<<"輸入棋盤的size(大小必須是2的n次冪): "; cin>>size; if(fuc(size)!=1){ cout<<"輸入錯誤,"; goto flag; } flag2: cout<<"輸入特殊方格位置的行號與列號(從0開始): "; cin>>index_x>>index_y; if (index_x >= size||index_y>=size){ cout<<"特殊方格位置超出棋盤范圍,"; goto flag2; } chessBoard ( 0,0,index_x,index_y,size ); for ( int i=0; i<size; i++ ) { for ( int j=0; j<size; j++ ){
cout<<board[i][j]<<"\t"; } cout<<endl<<endl; }
//輸出到文件 for ( int i=0; i<size; i++ ) { for ( int j=0; j<size; j++ ){
outfile<<board[i][j]<<"\t"; } outfile<<endl<<endl; } cout<<"最后一次棋盤覆蓋結果已輸出到output.txt中"<<endl; outfile.close() ; menu(); } void menu() { char c; cout<<"是否繼續輸入(Y/N)?"; cin>>c; if( c == 'Y'||c == 'y') input(); } void main() { input(); } |
||
測試數據: Size=8 特殊方格位置的行號:3,4
本次實驗程序運行結果如下: Output.txt: 3 3 4 4 8 8 9 9
3 2 2 4 8 7 7 9
5 2 6 6 10 10 7 11
5 5 6 1 0 10 11 11
13 13 14 1 1 18 19 19
13 12 14 14 18 18 17 19
15 12 12 16 20 17 17 21
15 15 16 16 20 20 21 21
|
||
因為采用的是C++的控制台程序,所以不能以圖形方式輸出,結果還不夠直觀。並且在控制台界面的輸出方格數目不能太多,所以我將最后一次輸出結果寫入了output.txt文件中,這樣可以使顯示的方格數更多! |