java红与黑算法_AcWing 1113. 红与黑-Java解法(DFS、BFS)

BFS解法

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.LinkedList;

import java.util.Queue;

public class Main {

private static int count = 1;

private static int[] dx = {-1, 0, 1, 0};

private static int[] dy = {0, 1, 0, -1};

public static void main(String[] args) throws IOException {

BufferedReader read = new BufferedReader(new InputStreamReader(System.in));

//支持多组数据测试

while (true) {

String[] s1 = read.readLine().split(" ");

int n = Integer.parseInt(s1[0]);

int m = Integer.parseInt(s1[1]);

if (n == 0 && m == 0) break;

int startX = 0, startY = 0;

Character[][] chs = new Character[m][n];

for (int x = 0; x < chs.length; x++) {

char[] s = read.readLine().toCharArray();

for (int y = 0; y < chs[x].length; y++) {

if (s[y] == '@') {

startX = x;

startY = y;

}

chs[x][y] = s[y];

}

}

count = 1;

bfs(chs, startX, startY);

System.out.println(count);

}

}

public static void bfs(Character[][] chs, int startX, int startY) {

chs[startX][startY] = '!';

//存放符合条件的结果

Queue queue = new LinkedList<>();

queue.offer(new int[]{startX, startY});

while (!queue.isEmpty()) {

int[] poll = queue.poll();

int x = poll[0], y = poll[1];

for (int i = 0; i < 4; i++) {

x = x + dx[i];

y = y + dy[i];

if (x >= 0 && x < chs.length && y >= 0 && y < chs[0].length && chs[x][y] == '.') {

queue.offer(new int[]{x, y});

chs[x][y] = '!';

count++;

}

//恢复坐标

x = x - dx[i];

y = y - dy[i];

}

}

}

}

DFS解法

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class Main {

private static int count = 0;

private static int[] dx = {-1, 0, 1, 0};

private static int[] dy = {0, 1, 0, -1};

public static void main(String[] args) throws IOException {

BufferedReader read = new BufferedReader(new InputStreamReader(System.in));

//支持多组数据测试

while (true) {

String[] s1 = read.readLine().split(" ");

int n = Integer.parseInt(s1[0]);

int m = Integer.parseInt(s1[1]);

if (n == 0 && m == 0) break;

int startX = 0, startY = 0;

Character[][] chs = new Character[m][n];

for (int x = 0; x < chs.length; x++) {

char[] s = read.readLine().toCharArray();

for (int y = 0; y < chs[x].length; y++) {

if (s[y] == '@') {

startX = x;

startY = y;

}

chs[x][y] = s[y];

}

}

count = 0;

chs[startX][startY] = '.';

dfs(chs, startX, startY);

System.out.println(count);

}

}

public static void dfs(Character[][] chs, int startX, int startY) {

if (startX >= 0 && startX < chs.length && startY >= 0 && startY < chs[0].length && chs[startX][startY] == '.') {

count++;

chs[startX][startY] = '!';

for (int i = 0; i < 4; i++) dfs(chs, startX + dx[i], startY + dy[i]);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值