代码如下:
1 #include <iostream> 2 using namespace std; 3 struct Node 4 { 5 int x,y; 6 }; 7 int a[100][100],h,w; 8 //队列 9 struct Queue 10 { 11 Node a[100]; 12 int front; 13 int rear; 14 } q; 15 int n=50;//存实际占用空间为n+1,即0-n。 16 //队满 17 bool isfull() 18 { 19 return (q.rear+1)%(n+1)==q.front; 20 } 21 //队空 22 bool isempty() 23 { 24 return q.rear==q.front; 25 } 26 //入队 27 void inq(Node x) 28 { 29 if(!isfull()) 30 { 31 q.a[q.rear]=x; 32 q.rear= (q.rear+1)%(n+1); 33 } 34 else 35 { 36 cout<<"The queue is full."; 37 } 38 } 39 //出队 40 Node outq() 41 { 42 Node t; 43 t=q.a[q.front]; 44 q.front=(q.front+1)%(n+1); 45 return t; 46 47 } 48 void mark(Node t_n) 49 { 50 Node t; 51 a[t_n.x][t_n.y]=2; 52 if(t_n.x-1>=0) 53 { 54 t.x=t_n.x-1; 55 t.y=t_n.y; 56 if(a[t.x][t.y]==1) 57 { 58 inq(t); 59 } 60 } 61 if(t_n.y-1>=0) 62 { 63 t.x=t_n.x; 64 t.y=t_n.y-1; 65 if(a[t.x][t.y]==1) 66 { 67 inq(t); 68 } 69 } 70 if(t_n.x+1<w) 71 { 72 t.x=t_n.x+1; 73 t.y=t_n.y; 74 if(a[t.x][t.y]==1) 75 { 76 inq(t); 77 } 78 } 79 if(t_n.y+1<h) 80 { 81 t.x=t_n.x; 82 t.y=t_n.y+1; 83 if(a[t.x][t.y]==1) 84 { 85 inq(t); 86 } 87 } 88 while(!isempty()) 89 { 90 mark(outq()); 91 } 92 } 93 main() 94 { 95 q.front=0; 96 q.rear=0; 97 int c=0; 98 cin>>h>>w; 99 for(int i=0; i<h; i++) 100 { 101 for(int j=0; j<w; j++) 102 { 103 cin>>a[i][j]; 104 } 105 } 106 for(int i=0; i<h; i++) 107 { 108 for(int j=0; j<w; j++) 109 { 110 if(a[i][j]==1) 111 { 112 Node t; 113 t.x=i; 114 t.y=j; 115 mark(t); 116 c++; 117 } 118 } 119 } 120 cout<<c; 121 }
运行效果1:
运行效果2:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现