不知道有沒有人最近也是測這題一直WA
我在另個網站是AC的,在這裡測第22行一直過不了...
以下是小弟我的程式碼
#include <cstdio>
#include <algorithm>
char world[20][20];
bool visited[20][20];
void DFS(int r,int c, int row,int col)
{
visited[r][c] = true;
if(r+1<row && world[r+1][c]==world[r][c] && !visited[r+1][c]) DFS(r+1,c,row,col);
if(c+1<col && world[r][c+1]==world[r][c] && !visited[r][c+1]) DFS(r,c+1,row,col);
if(r-1>=0 && world[r-1][c]==world[r][c] && !visited[r-1][c]) DFS(r-1,c,row,col);
if(c-1>=0 && world[r][c-1]==world[r][c] && !visited[r][c-1]) DFS(r,c-1,row,col);
}
struct language
{
int freq = 0;
char name;
};
bool comp(const language& a,const language& b)
{
if(a.freq!=b.freq) return a.freq > b.freq;
else return a.name < b.name;
}
int main()
{
int times;
scanf("%d",×);
int t = 0;
while(t < times)
{
t++;
language Ls[26];//record the frequency of languages
int l=0;
for(l=0;l<26;l++)
Ls[l].name = 'a'+l;
int row,col;
scanf("%d%d",&row,&col);
getchar();//keep out \n
//input
int i=0,j=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%c",&world[i][j]);//remember to keep out \n when inputing chars
visited[i][j] = false;
}
getchar();
}
//using DFS to find each area
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(!visited[i][j])
{
Ls[ world[i][j]-'a'].freq++;
DFS(i,j,row,col);
}
}
}
std::sort(Ls,Ls+26,comp);
printf("World #%d\n",t);
for(i=0;i<26 && Ls[i].freq > 0;i++)
{
printf("%c: %d\n",Ls[i].name,Ls[i].freq);
}
}
}
陣列開大一點就會過了
UVA測資比較弱的樣子