アットウィキロゴ

Red and Black

1130 : Red and Black



解説


プログラム

C


C++

#include<iostream>
using namespace std;

int count;
char map[21][21];
int w,h;


void search(int x,int y){

	map[y][x] = '#';
	count++;
	if(x+1 < w && map[y][x+1] == '.'){
		search(x+1,y);
	}
	if(x-1 >= 0 && map[y][x-1] == '.'){
		search(x-1,y);
	}
	if(y-1 >= 0 && map[y-1][x] == '.'){
		search(x,y-1);
	}
	if(y+1 < h && map[y+1][x] == '.'){
		search(x,y+1);
	}

	return;

}

int main(){

	while(cin >> w >> h,w||h){

		count = 0;

		for(int i = 0; i < h; i++){
			cin >> map[i];
		}

		int sx,sy;

		for(int i = 0; i < h; i++){
			for(int j = 0; j < w; j++){
				if(map[i][j] == '@'){
					sx = j;
					sy = i;
				}
			}
		}

		search(sx,sy);
		cout << count << endl;
	}
	return 0;
}

Java

import java.util.Scanner;
public class RedAndBlack1130 {
static int w,h,count;
static char[][] map;
static void move(int y,int x){
	map[y][x]='#';
	count++;
	if(0<y){
		if(map[y-1][x]!='#') move(y-1,x);//↑
	}
	if(x<w-1){
		if(map[y][x+1]!='#') move(y,x+1);//→
	}
	if(0<x){
		if(map[y][x-1]!='#') move(y,x-1);//←
	}
	if(y<h-1){
		if(map[y+1][x]!='#') move(y+1,x);//↓
	}
}
public static void main(String[] args){
	Scanner scan=new Scanner(System.in);
	while(true){
		w=scan.nextInt(); h=scan.nextInt();
		if(w==0&&h==0) break;
		
		int sx=-1;
		int sy=-1;
		map=new char[h][w];
		for(int i=0;i<h;i++){
			String s=scan.next();
			for(int j=0;j<w;j++){
				map[i][j]=s.charAt(j);
				if(s.charAt(j)=='@'){
					sx=j;sy=i;
				}
			}
		}
		move(sy,sx);
		System.out.println(count);
		count=0;
	}
}
}
最終更新:2012年12月10日 23:05