POJ_1979 Red and Black
問題
'@'から縦横に進んでいけるマスの個数をもとめよ
解法
深さ優先探索をしてもとめる
#include <cstdio> #include <algorithm> using namespace std; const int MAX_HW = 20; char a[MAX_HW + 2][MAX_HW + 2]; int H, W, sx, sy; const int dx[] = { -1, 0, 0, 1}; const int dy[] = { 0, -1, 1, 0}; int solve(int x, int y){ a[x][y] = '#'; int res = 1; for(int i = 0; i < 4; i++){ int nx = x + dx[i], ny = y + dy[i]; if(a[nx][ny] == '.') res += solve(nx, ny); } return res; } int main(){ char c; while(scanf("%d %d", &W, &H) && H){ for(int i = 0; i <= H + 1; i++){ a[0][i] = '#'; a[W + 1][i] = '#'; } for(int i = 0; i <= W + 1; i++){ a[i][0] = '#'; a[i][H + 1] = '#'; } for(int i = 1; i <= H; i++){ scanf("%c", &c); for(int j = 1; j <= W; j++){ scanf("%c", &a[j][i]); if(a[j][i] == '@'){ sx = j; sy = i; } } } printf("%d\n", solve(sx, sy)); } return 0; }