Red and Black POJ - 1979
Red and Black POJ - 1979
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can’t move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
题目大意说的是给你一个初始点@(算作黑色),可以往四个方向走,只能走*(黑色),不能走#(红色),问你最后可以可以走的黑色的总和
联通块问题:
我们只要从输入的时候记下起始点的位置,然后模拟,往四个方向走,#可以不走了,是*就继续走,递归返回步数
处理一下细节问题,把走过的格子标记一下,不能走回头路,最后递归返回的就是最后的总数
同时注意是否越界
代码
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define pi acos(-1)
const int inf = 0x3f3f3f3f;
int dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
char s[25][25];
int vis[25][25];
int w,h;
int sx,sy;
int DFS(int i,int j){
int cnt=1;
vis[i][j]=1;
for(int k=0;k<4;k++){
int x=i+dir[k][0];
int y=j+dir[k][1];
if(vis[x][y]||s[x][y]=='#'){
continue;
}
if(x<h&&x>=0&&y>=0&&y<w){
cnt+=DFS(x,y);
}
}
return cnt;
}
int main()
{
while(~scanf("%d%d",&w,&h)&&w&&h){
sx=-1,sy=-1;
memset(vis,0,sizeof(vis));
for(int i=0;i<h;i++){
scanf("%s",s[i]);
if(sx==-1){
for(int j=0;j<w;j++){
if(s[i][j]=='@'){
sx=i;
sy=j;
}
}
}
}
printf("%d\n",DFS(sx,sy));
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现