问题 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;
}