题目描述
blablabla
样例
blablabla
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
#include<iostream>
#include<cstring>
using namespace std;
const int N = 22;
char g[N][N];
bool st[N][N];
int n, m;
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
void dfs(int x, int y, int &u)
{
u ++;
st[x][y] = true;
for (int i = 0; i < 4; i ++)
{
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= m) continue;
if (st[a][b]) continue;
if (g[a][b] == '#') continue;
dfs(a, b, u);
}
}
int main()
{
int T;
while(cin >> m >> n , m || n)
{
for (int i = 0; i < n; i ++) cin >> g[i];
memset(st, 0, sizeof st);
int x, y;
for (int i = 0; i < n; i ++)
for (int j = 0; j < m; j ++)
if (g[i][j] == '@')
{
x = i, y = j;
break;
}
int res = 0;
dfs(x, y, res);
cout << res << endl;
}
return 0;
}
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
#include<iostream>
#include<cstring>
using namespace std;
const int N = 22;
char g[N][N];
bool st[N][N];
int n, m;
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
int dfs(int x, int y)
{
int cnt = 1;
st[x][y] = true;
for (int i = 0; i < 4; i ++)
{
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= m) continue;
if (st[a][b]) continue;
if (g[a][b] == '#') continue;
cnt += dfs(a, b);
}
return cnt;
}
int main()
{
int T;
while(cin >> m >> n , m || n)
{
for (int i = 0; i < n; i ++) cin >> g[i];
memset(st, 0, sizeof st);
int x, y;
for (int i = 0; i < n; i ++)
for (int j = 0; j < m; j ++)
if (g[i][j] == '@')
{
x = i, y = j;
break;
}
cout << dfs(x, y) << endl;
}
return 0;
}