hdu-1312 Red and Black(dfs)

題目鏈接http://acm.hdu.edu.cn/showproblem.php?pid=1312

題目大意:點是路,#是牆,輸出從起始位置能走多少步

題解:dfs函數兩個參數x,y記錄當前座標。從起始位置開始深搜,如果當前位置是‘#’則不進行下一步搜索,如果是 。 則把sum+1,並且將該位置 置爲 ‘#’ 進行下一步深搜(搜索上下左右的座標點)

AC代碼

#include <iostream>
#include"math.h"
#include"string.h"
#include"algorithm"
using namespace std;
int sum = 0;
char map[25][25] = {'#'};
int w,h;
int startx,starty;         

void dfs(int x,int y){
    if(map[x][y] == '#')    return;
    else{
        map[x][y] = '#';
        sum++;
    }
    dfs(x+1,y);
    dfs(x-1,y);
    dfs(x,y+1);
    dfs(x,y-1);
}

int main(int argc, char** argv) {    
    while(cin>>w>>h){
        if(w == h && w == 0)    break;
        memset(map,'#',625);
        sum = 0;
        for(int i = 1;i<=h;i++)
            for(int j = 1;j<=w;j++) {
                cin>>map[i][j];
                if(map[i][j] == '@'){
                    startx = i;
                    starty = j;
                    map[i][j] = '.';
                }
            }
        dfs(startx,starty);
        cout<<sum<<endl;
    }
    return 0;
}

小結:很普通的一道dfs題目 技巧點在於講邊界初始化爲 牆(‘#’)這樣就不用額外做邊界判斷。dfs函數的要點在於將走過的路堵死(置爲‘#’)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章