HDU 1312 Red and Black(经典DFS)

2023-05-20,,

嗯...

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

一道很经典的dfs,设置上下左右四个方向,读入时记下起点,然后跑dfs即可...最后答案加上起点的1,无需回溯!!

AC代码:

 #include<cstdio>
#include<iostream>
#include<cstring> using namespace std; int dir[][] = {{-, }, {, }, {, -}, {, }}; int n, m, ans;
bool flag[][];
char g[][]; inline void dfs(int x, int y){
for(int i = ; i < ; i++){
int nx = x + dir[i][];
int ny = y + dir[i][];
if(nx <= m && ny <= n && nx > && ny > && !flag[nx][ny] && g[nx][ny] == '.'){
ans++;
flag[nx][ny] = ;
dfs(nx, ny);
}
}
} int main(){
while(~scanf("%d%d", &n, &m) && n != && m != ){
int x, y;
memset(flag, , sizeof(flag));
for(int i = ; i <= m; i++){
for(int j = ; j <= n; j++){
cin >> g[i][j];
if(g[i][j] == '@'){ x = i; y = j;}
}
}
ans = ;
flag[x][y] = ;
dfs(x, y);
printf("%d\n", ans + );
}
return ;
}

AC代码

HDU 1312 Red and Black(经典DFS)的相关教程结束。

《HDU 1312 Red and Black(经典DFS).doc》

下载本文的Word格式文档,以方便收藏与打印。