Red and Black HDU 1312
程序员文章站
2022-05-21 18:15:43
...
题目链接点击这里Red and Black
使用方法:递归的深度优先遍历和非递归的深度优先遍历两种实现方式
代码:
import java.io.*;
import java.util.Stack;
import java.util.Scanner;
public class Main {
private static Scanner in = new Scanner(System.in);
private static char [][]matrix;
private static int sum;
private static int w;
private static int h;
private static int []a = {1,-1,0,0};
private static int []b = {0,0,-1,1};
private static boolean isLegal(int x,int y){
if(x<0 || x>=h || y<0 || y>=w) return false;
return true;
}
// 递归的dfs
// private static void dfs(int x,int y){
// if(matrix[x][y]=='.') {
// sum++;
// matrix[x][y] = '*';
// }
// for(int i=0;i<4;i++)
// {
// int dx = x + a[i];
// int dy = y + b[i];
// if(judge(dx,dy) && matrix[dx][dy]=='.'){
// dfs(dx,dy);
// }
// }
// }
private static class Point{
int x,y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
//非递归的dfs
private static void dfs(int x , int y){
Stack<Point> stack = new Stack<>();
stack.add(new Point(x,y));
while(!stack.isEmpty()){
Point p = stack.pop();
x = p.x;
y = p.y;
if(matrix[x][y]=='.'){
sum++;
matrix[x][y] = '*';
}
for(int i=0; i<4; i++)
{
int dx = x + a[i];
int dy = y + b[i];
if(isLegal(dx,dy)){
if(matrix[dx][dy]=='.'){
stack.push(new Point(dx,dy));
}
}
}
}
}
public static void main(String[] args) throws IOException{
w = in.nextInt();
h = in.nextInt();
String str;
int x=0,y=0;
while(w!=0 || h!=0){
matrix = new char[h][w];
for(int i=0;i<h;i++)
{
str = in.next();
for(int j=0;j<w;j++)
{
matrix[i][j] = str.charAt(j);
if(matrix[i][j]=='@'){
x = i;
y = j;
}
}
}
sum = 0;
dfs(x,y);
System.out.println(sum+1);
w = in.nextInt();
h = in.nextInt();
}
}
}
下一篇: php图片添加水印示例
推荐阅读
-
POJ 1979 Red And Black 红与黑DFS深搜 AC代码C++
-
ZOJ4048 Red Black Tree(The 2018 ACM-ICPC Asia Qingdao Regional Contest, Online,二分+LCA)
-
POJ3364 HDU1802 UVA11231 Black and white painting【数学】
-
Red and Black HDU 1312
-
Red and Black(DSF)
-
基础数据结构和算法十一:Red-black binary search tree
-
Red and Black——个人c++解
-
Red and Black-----BFS(水题)
-
dfs/bfs--Red and Black
-
POJ1979 Red and Black【DFS】