2021个人训练赛第13场 问题 B: Visibility(模拟)

该博客介绍了一道编程题目,题目要求在给定的二维矩阵中,计算从特定坐标出发能看到的没有障碍物的点的数量。输入包含矩阵的尺寸和特定坐标的行和列,矩阵由'.'和'#'字符表示,'.'表示无障碍,'#'表示障碍。解题思路是通过模拟从给定坐标向上下左右四个方向遍历,遇到障碍物则停止,累计计数。博主给出了AC代码示例,代码中通过四个循环分别检查右、左、上、下四个方向的可见点,并在遇到障碍物时停止计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题 B: Visibility

题目描述

We have a grid of H horizontal rows and W vertical columns, where some of the squares contain obstacles.
Let (i,j) denote the square at the i-th row from the top and j-th column from the left.You are given H strings S1,S2,S3,…,SH. The j-th character of Si describes the square (i,j); # means the square contains an obstacle, and . means it does not.
We say a square is visible from another when it is on the same row or the same column, and there is no obstacle between them (including themselves).
Print the number of squares visible from the square (X,Y) (including (X,Y) itself).

Constraints
1≤H≤100
1≤W≤100
1≤X≤H
1≤Y≤W
Si is a string of length W consisting of . and #.
The square (X,Y) does not contain an obstacle.

输入

Input is given from Standard Input in the following format:
H W X Y
S1
S2
S3

SH

输出

Print the answer.

样例输入

【样例1】
4 4 2 2
##…
…#
#.#.
.#.#
【样例2】
3 5 1 4
#…

…#
【样例3】
5 5 4 2
.#…#
#.###
##…
#…#.
#.###

样例输出

【样例1】
4
【样例2】
4
【样例3】
3

提示

样例1解释
The squares visible from the square (2,2) are:
(2,1)
(2,2)
(2,3)
(3,2)
样例2解释
Even if two squares are on the same row or the same column, they are not visible from each other when there are obstacles between them.

解题思路:

读懂题,模拟即可。
题意是说给你一个h行w列的矩阵,其中“#”代表障碍物,“.”代表通着的点,现在给你一个坐标(下标从1开始),找到他能看见的点(这个点所在的行、列)的个数。
所以直接模拟,四个循环分别枚举这个坐标点上下左右有多少个连续的“.”,遇到“#”停止。

AC代码:

#include <iostream>
using namespace std;
const int N=110;
char g[N][N];
int main()
{
	int h,w,x,y;
	cin>>h>>w>>x>>y;
	int res=0;
	for(int i=1;i<=h;i++)
	{
		for(int j=1;j<=w;j++)
		{
			cin>>g[i][j];
		}
	}
	
	//从坐标点向右寻找 
	for(int i=y+1;i<=w;i++)
	{
		if(g[x][i]=='#')
		break;
		else
		res++;
	}
	
	//从坐标点向左寻找 
	for(int i=y-1;i>=1;i--)
	{
		if(g[x][i]=='#')
		break;
		else
		res++;
	}
	
	//从坐标点向下寻找 
	for(int i=x+1;i<=h;i++)
	{
		if(g[i][y]=='#')
		break;
		else
		res++;
	}
	
	//从坐标点向上寻找 
	for(int i=x-1;i>=1;i--)
	{
		if(g[i][y]=='#')
		break;
		else
		res++;
	}
	
	cout<<res+1;//最后不要忘记坐标点本身也算一个 
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值