跳到主要內容

[程式競賽] UVa 572, Oil Deposits,Flood Fill 演算法

原題目簡述如下:
以 m x n 大小的 grid 代表一張地圖,現今要在此地圖內探勘,找出油田。某一區塊如果標示 "@" 代表有油,"*" 代表沒有油。
"@" 相鄰的區域的聯集,可視為一個油田。(所謂相鄰,除了上下左右,斜向的相鄰也算進去)
求任意地圖中,油田的個數。

例如輸入的測資為:
*    *   *    *  @
*   @  @  *  @
*   @   *   *  @
@ @  @   * @
@ @   *   *  @

則油田個數為 2。

想法
採用典型的倒水演算法(Flood Fill),走訪 "@" 出現的區域,從此往下倒水,倒過水的區域標上 id,因此透過 id 的編號,可以得知油田的個數。

實作
先實作倒水演算法的子函式:
void floodfill(vector<vector<char> >& map,
               vector<vector<int>  >& id_table,
               int row, int col, int id)
{
   if(row < 0 || (row >= map.size()) )   return;
   if(col < 0 || (col >= map[0].size())) return;
   if(map[row][col] != '@' || id_table[row][col] > 0) return;

   id_table[row][col] = id;
   floodfill(map, id_table, row-1, col-1, id);
   floodfill(map, id_table, row-1, col,   id);
   floodfill(map, id_table, row-1, col+1, id);
   floodfill(map, id_table, row,   col-1, id);
   floodfill(map, id_table, row,   col+1, id);
   floodfill(map, id_table, row+1, col-1, id);
   floodfill(map, id_table, row+1, col,   id);
   floodfill(map, id_table, row+1, col+1, id);
}


我透過 2D vector 來代表地圖,傳入要倒水位置的 row 和 column index,並先判斷當前位置是否出界,以及透過當前位置的 id 判斷是否已經被走訪過。如果沒有被走訪過,則標上新的 id 號碼,遞迴走訪相鄰 8 個區域。

在 main 主程式的部份,先做 stdin IO 將地圖讀入,動態地宣告 vector 陣列,然後將沒有走訪過的 "@" 區域,傳入 floodfill 開始倒水就可以了:
int main(int argc, char** argv)
{
    int m, n;
    string line;
    while(getline(cin, line))
    {
        istringstream token(line);
        token >> m >> n;
        if(m == 0 && n == 0) break;

        vector<vector<char> > map(m, vector<char>(n));
        vector<vector<int> >  id_table(m, vector<int>(n,0));

        for(int i=0; i<m; i++)
        {
            getline(cin, line);
            for(int j=0; j<n; j++)    map[i][j] = line[j];  
        }

        int id = 1;
        for(int i=0; i<m; i++)
        {
            for(int j=0; j<n; j++)
            {
               if(map[i][j] == '@' && id_table[i][j] == 0)
               {
                   floodfill(map, id_table, i, j, id);
                   id++;
               }
            }
        }
        cout << (id-1) << endl;

    }
    return 0;

上傳 online judge 執行成功:
#ProblemVerdictLanguageRun TimeSubmission Date
23784822572Oil DepositsAcceptedC++0.0002019-08-18 09:49:42

留言

這個網誌中的熱門文章

[Linux] Elementary OS 字體調校

用 gesetting 取得 elementary os 的等寬字體(這也是終端機默認字體): gsettings get org.gnome.desktop.interface monospace-font-name 會顯示目前字型跟字體大小: Roboto Mono 10 設定字體大小: gsettings set org.gnome.desktop.interface monospace-font-name 'Roboto Mono 12' 可以微調 text-scaling-factor: gsettings set org.gnome.desktop.interface text-scaling-factor <value>

[Python] print 同時輸出到 file 和 console

在 Python 撰寫程式時,我們會希望螢幕 stdout 輸出可以同時記錄到 log 檔案裡。 但是螢幕輸出可能含有 ASCII escape codes 的顏色資訊,輸出的 log 檔案會有類似 ^[[01;32m 這種字樣出現。 我採用比較簡單的解法: 先將 print 函式輸出的訊息,同時導向到螢幕,同時儲存在指定的 log.txt 檔案中。 再用 sed 指令,將 log.txt 內的 ASCII escape code 清除。 方法如下: import sys class PrintLog(object): def __init__(self): self.console = sys.stdout self.log_file = open("log.txt", "w") def write(self, msg): self.console.write(msg) self.log_file.write(msg) def flush(self): pass def main(): original_stdout = sys.stdout sys.stdout = PrintLog() print " This is a testing message." sys.stdout = original_stdout if(__name__ == "__main__"): main() 也就是將 sys.stdout 指向自定義的 PrintLog class,讓 PrintLog 來處理輸出文字,用完 PrintLog 後再把 sys.stdout 導向回原本的 stdout。 接著使用 sed 指令刪除 log.txt 的 ASCII escape code: sed -i 's/\x1b[^m]*m//g' ./log.txt 上面的正規,\x 後面用來接一個 16 進位 ASCII 編碼,其中 1b 代表的是 ESC 退出鍵。 到此即可獲得沒有顏色編碼的 log.tx...

[C++] 計算程式執行時間:clock 和 time 函式

要計算一段程式碼執行時間,可以用 time 函式: 1 2 3 4 5 time_t start, end; start = time(NULL); // DO SOMETHING... end = time(NULL); cout " [Msg] total time: " difftime(end, start) " sec" endl; time 函式的精確度只到達秒,如果要精確到毫秒等級,要用 clock 函式: 1 2 3 4 5 6 clock_t start, end; start = clock(); // DO SOMETHING... end = clock(); cout ( double )(finish - start) / CLOCKS_PER_SEC endl;