Subject to the effect
There is a rectangular room, covered with square tiles. Each tile are colored red or black. A man standing on a black tile. He can move from one block to one of four adjacent tiles. But he can not move on the red tile, can only move on a black tile.
Write a program to calculate the number of black tiles he can reach by repeating the above action.
Entry
Comprising a plurality of input data sets. From the data set comprises two positive integers W and H line beginning; W and H are the number of tiles in the x and y directions. W and H does not exceed 20.
There dataset H lines each containing W characters. Each character represents the color of the tile, as follows.
'. '- black tile
'#' - red square
'@' - a man on a black tile (appears only once in the dataset)
Ideas analysis
- Note that w, h, the relationship between the input and the determination of the border need to pay attention
- dfs must have vis array, or children and grandchildren are also endless.
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<string.h>
using namespace std;
#define MAX 25
int w, h, arr[MAX][MAX], vis[MAX][MAX];//长,宽,地图,该点是否已经走过
int sx, sy, res;//人开始行走的位置,能到达的红点数目
int dx[4] = { 0,0,1,-1 }, dy[4] = { 1,-1,0,0 };
bool check(int x, int y) {
if (x >= 1 && x <= h && y >= 1 && y <= w && arr[x][y] != 0)return true;
else return false;
}
void dfs(int x, int y) {
vis[x][y] = 1; res++;
for (int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i];
if (check(xx, yy) && !vis[xx][yy]) {
dfs(xx, yy);
}
}
}
int main() {
while (cin >> w >> h && w + h > 0) {//w:宽 h:高
res = 0;
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= h; i++)
for (int j = 1; j <= w; j++)
{
char s; cin >> s;
if (s == '.')arr[i][j] = 1;
else if (s == '#') arr[i][j] = 0;
if (s == '@') { sx = i, sy = j; }
}
dfs(sx, sy);
cout << res << endl;
}
}