閱讀579 返回首頁    go 技術社區[雲棲]


POJ1979-Red and Black

Red and Black
Time Limit: 1000MS  Memory Limit: 30000K
Total Submissions: 22250  Accepted: 12011

Description

There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles.

Write a program to count the number of black tiles which he can reach by repeating the moves described above.

Input

The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.

There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.

'.' - a black tile
'#' - a red tile
'@' - a man on a black tile(appears exactly once in a data set)
The end of the input is indicated by a line consisting of two zeros.

Output

For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
Sample Output

45
59
6
13

Source

Japan 2004 Domestic

 

 

問題描述:有一間長方形的房子,地上鋪了紅色、黑色兩種顏色的正方形瓷磚。你站在其中一塊黑色的瓷磚上,隻能向相鄰的黑色瓷磚移動。請寫一個程序,計算你總共能夠到達多少塊黑色的瓷磚。

算法:設f(x,y)為從點(x,y)出發能夠走過的黑瓷磚總數,則
f(x,y) = 1+f(x-1,y)+f(x+1,y)+f(x,y-1)+f(x,y+1)
這裏需要注意,凡是走過的瓷磚不能夠被重複走過

AC代碼:

#include<stdio.h>
#include<string.h>
//方塊四周加白色塊,去掉邊界判斷,
//使得遞歸統一終止於白色塊
int Rank[22][22];
int FindBlack(int c,int l)
{
   if(Rank[c][l]==2)//出口條件(防止重複走)
   return 0;
   else Rank[c][l]=2;
   return 1+FindBlack(c+1,l)+FindBlack(c-1,l)+FindBlack(c,l-1)+FindBlack(c,l+1);//遞歸函數
}
int main()
{
    int i,j,c,l,n,m;
    char x;
    while(scanf("%d %d",&m,&n),n!=0&&m!=0)
    {
       max=0;
       for(i=0;i<22;i++)
       for(j=0;j<22;j++)
       Rank[i][j]=2;
       for(i=1;i<=n;i++)
       {  
          getchar();
          for(j=1;j<=m;j++)
          {  
              scanf("%c",&x);
              if(x=='.')
              Rank[i][j]=1;
              else
              {
                 if(x=='#')
                 Rank[i][j]=2;
                 else
                 {
                     c=i;l=j;
                     Rank[i][j]=1; 
                 }
              }
          }
       }
       printf("%d\n",FindBlack(c,l));
    }
    return 0;
}

最後更新:2017-04-03 05:39:37

  上一篇:go 九度題目1447:最短路
  下一篇:go poj 2039 To and Fro【字符數組操作】