#include <iostream> #include <string> using namespace std; int row,col; int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}}; char map[20][20]; bool vised[20][20]; void dfs(int posX,int posY) { for (int i = 0; i != 4; ++ i) { int offX,offY; offX = posX + dir[i][0];//i先为0,x方向移动0, offY = posY + dir[i][1];//i先为0,y方向移动-1 if (offX >= 0 && offX < row && offY >= 0 && offY < col) { if (!vised[offX][offY] && map[offX][offY] == ‘.‘) { //cout<<"x is :"<<offX<<" "<<"y is :"<<offY<<endl; vised[offX][offY] = true; dfs(offX, offY); } } } } int main() { while (cin>>col>>row) { int sX = 0,sY = 0; int cnt = 0; if (row <= 0 || col <= 0) { break; } memset(vised, false, sizeof(vised)); //map for (int i = 0; i != row; ++ i) { for (int j = 0; j != col; ++ j) { cin>>map[i][j]; if (map[i][j] == ‘@‘) { sX = i; sY = j; } } } vised[sX][sY] = 1; dfs(sX,sY); for (int i = 0; i != row; ++ i) { for (int j = 0; j != col; ++ j) { if (vised[i][j]) { cnt ++; } } } cout<<cnt<<endl; } return 0; }
dfs深度遍历。
时间: 2024-10-18 08:42:10