Problem ID:1016 Red and Black
簡單題意:給出一個地圖,其中有一個起始點,標記爲"."的地方可以走,爲"#"的不能走。只能直走,不能斜向前進。求能到達的所有地區數。
解題思路形成過程:利用DFS,找出能到達的所有"."地區,每找到一個進行標記,從而剪枝、減少重複計算。
因此,此題遞歸共有3個條件:①:所遍歷到的行、列不能超出地圖範圍;
②:所遍歷到的地區必須爲"."標記;
③:此地區在之前的遍歷過程中沒有沒標記過;
感想: 注意細節,因爲一個變量名輸錯了,導致編譯沒錯但是運行結果有錯,找了好久才發現。
注意初始時輸入的行數和列數的順序。
代碼:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int cmap[21][21];
bool mark[21][21];
int dir[4][2]={{-1,0},{0,-1},{0,1},{1,0}};//上、左、右、下
int w,h;
int dfs(int r,int c)
{
int num=1;
for(int i=0;i<4;++i)
{
int temp_r=r;
int temp_c=c;
temp_r+=dir[i][0];
temp_c+=dir[i][1];
if(temp_r>=0&&temp_r<h&&temp_c>=0&&temp_c<w){
if(cmap[temp_r][temp_c]==2&&mark[temp_r][temp_c]==false){
mark[temp_r][temp_c]=true;
num+=dfs(temp_r,temp_c);
}
}
}
return num;
}
int main()
{
freopen("1.txt","r",stdin);
while(scanf("%d%d",&w,&h)!=EOF)
{
if(w==0)
return 0;
memset(mark,false,sizeof(mark));
int r_s,c_s;
for(int i=0;i<h;++i)
for(int j=0;j<w;++j){
char temp;
cin>>temp; //如果用scanf("%c",&temp);會出現錯誤,需要考慮輸入中的回車問題。
if(temp=='@'){
cmap[i][j]=1;
r_s=i;
c_s=j;
}
else if(temp=='.')
cmap[i][j]=2;
else if(temp=='#')//此條件語句可不寫。
cmap[i][j]=3;
}
mark[r_s][c_s]=true;
int cnt=dfs(r_s,c_s);
printf("%d\n",cnt);
}
}