以下是我自己编的代码,但是找不出问题所在,大神求解
题目:Description
Once there was a king named Akbar. He had a son named Shahjahan. For an unforgivable reason the king wanted him to leave the kingdom. Since he loved his son he decided his son would be banished in a new place. The prince became sad, but he followed his father's will. In the way he found that the place was a combination of land and water. Since he didn't know how to swim, he was only able to move on the land. He didn't know how many places might be his destination. So, he asked your help.
For simplicity, you can consider the place as a rectangular grid consisting of some cells. A cell can be a land or can contain water. Each time the prince can move to a new cell from his current position if they share a side.
Now write a program to find the number of cells (unit land) he could reach including the cell he was living.
Input
Input starts with an integer T (≤ 500), denoting the number of test cases.
Each case starts with a line containing two positive integers W and H; W and H are the numbers of cells in the x and y directions, respectively. W and H are not more than 20.
There will be H more lines in the data set, each of which includes W characters. Each character represents the status of a cell as follows.
1) '.' - land
2) '#' - water
3) '@' - initial position of prince (appears exactly once in a dataset)
Output
For each case, print the case number and the number of cells he can reach from the initial position (including it).
Sample Input
4
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
Sample Output
Case 1: 45
Case 2: 59
Case 3: 6
Case 4: 13
以下是我的代码:
程序代码:
#include <iostream> using namespace std; int t=0,r,k; int pr( char (*a)[20] ,int n,int m) { if(a[n][m]=='@') {t++;return 0;} if(a[n][m+1]=='.' && m+1<=k) if(pr(a,n,m+1)==0) return 0; if(a[n][m-1]=='.' && m-1>=0) if(pr(a,n,m-1)==0) return 0; if(a[n-1][m]=='.' && n-1>=0) if(pr(a,n-1,m)==0) return 0; if(a[n+1][m]=='.' && n+1<=r) if(pr(a,n+1,m)==0) return 0; if(a[n][m+1]=='@' && m+1<=k) {t++;return 0;} if(a[n][m-1]=='@' && m-1>=0) {t++;return 0;} if(a[n-1][m]=='@' && n-1>=0) {t++;return 0;} if(a[n+1][m]=='@' && n+1<=r) {t++;return 0;} return 0; } int num(int a[],int i) { if (i==0) return 0; return a[i-1]+num( a ,i-1); } int main () { int n,m,w[20]={0},i,T; char a[20][20]; cin >> T; for( i=0;i<T;i++) { cin >> r >> k; for(n=0;n<k;n++) for(m=0;m<r;m++) cin >> a[n][m]; for(n=0;n<k;n++) for(m=0;m<r;m++) pr(a,n,m); w[i]=t-num(w,i); } for (r=0;r<T;r++) { cout << w[r] << endl; } return 0; }