這有一間鋪滿方形瓷磚的長方形客房, 每塊瓷磚的顏色是紅色或者黑色, 一個人站在一塊黑色瓷磚上, 他可以從這塊瓷磚移動到相鄰(即,上下左右)的四塊瓷磚中的一塊, 但是他只能移動到黑色瓷磚上,而不能移動到紅色瓷磚上,
撰寫一個程式,通過重復上述動作來計算他可以達到的黑色瓷磚的數量,
Input輸入包含多組資料, 每組資料包含兩個正整數W和H; H表示瓷磚的行數,W表示瓷磚的列數, W和H不超過20,
瓷磚的顏色用字符表示,如下所示,
'.' - 黑色瓷磚
'#' - 紅色瓷磚
'@' - 站在黑色瓷磚上的人(每組資料中只有一個)
Output對于每組資料,你的程式應輸出一行,其中包含他可以到達的黑色瓷磚數目,(站著的黑色瓷磚也要包含在內)
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
Sample Output
45 59 6 13
代碼:
import java.util.Scanner; public class Main{ static int n,m,cnt; static final int N=1005; static char map[][]=new char[N][N]; static int dx[]={0,0,1,-1}; static int dy[]={1,-1,0,0}; static void dfs(int x,int y){ if(map[x][y]=='.'){ cnt++; map[x][y]='#'; } for(int i=0;i<4;i++){ int xx=x+dx[i]; int yy=y+dy[i]; if(xx<0 ||yy<0 ||xx>=n ||yy>=m) continue; if(map[xx][yy]=='#') continue; dfs(xx,yy); } } public static void main(String[] args) { Scanner scan=new Scanner(System.in); while(scan.hasNext()){ m=scan.nextInt(); n=scan.nextInt(); if(n==0 && m==0) break; for(int i=0;i<n;i++) map[i]=scan.next().toCharArray(); cnt=1; boolean flag=false; for(int i=0;i<n;i++){ for(int j=0;j<m;j++) if(map[i][j]=='@'){ dfs(i,j); flag=true; break; } if(flag) break; } System.out.println(cnt); } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/98369.html
標籤:其他
