標籤:hdu1241 java 廣度搜尋
import java.util.Scanner;public class Main{public static void main(String[] args) {Scanner sc = new Scanner(System.in);while (sc.hasNext()) {int m = sc.nextInt();//輸入地圖的行數int n = sc.nextInt();//輸入地圖的列數if (m == 0) {//若m=0則退出程式break;}// 初始化圖Plot[][] plots = new Plot[m][n];//用來表示地圖中每個點的資訊for (int i = 0; i < m; i++) {String str = sc.next(); //用來接受地圖for (int j = 0; j < n; j++) {//把每個點都賦值橫座標,縱座標,和地質情況plots[i][j] = new Plot();plots[i][j].x = i;plots[i][j].y = j;plots[i][j].c = str.charAt(j);}}// 搜尋,查看有幾個圖塊int count = 0;//表示探測到的油田的片數for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {//找到油田位置,並對其進行廣度搜尋if (plots[i][j].c == '@' && !plots[i][j].isVisited) {//地址為油田和沒有被搜尋過// 廣搜PlotQue queue = new PlotQue();queue.add(plots[i][j]);//把上面搜尋到的油田加入到隊列中bfs(plots, queue);count++;}}}System.out.println(count);//輸出油田的片數,即最後的結果}}private static void bfs(Plot[][] plots, PlotQue queue) {int px, py;int m = plots.length;int n = plots[0].length;while (!queue.isEmpty()) {//保證隊列不為空白Plot plot = queue.pop(); //彈出隊列的元素//在該元素周圍進行廣度搜尋for (int i = 0; i < 8; i++) {px = plot.x + dir[i][0];py = plot.y + dir[i][1];//不能越界,地質為油田和沒有被搜尋過if (px >= 0 && px < m && py >= 0 && py < n && plots[px][py].c == '@' && !plots[px][py].isVisited) {plots[px][py].isVisited = true;queue.add(plots[px][py]);}}}}final static int dir[][] = { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 },{ -1, -1 }, { 1, -1 }, { -1, 1 }, { 1, 1 } };//上,下,左,右,左上,右上,左下,右下}//用來每個點class Plot {int x, y;//表示點的位置char c; //表示點地質情況boolean isVisited = false; //表示該點是否被搜尋過} //隊列class PlotQue {Plot plots[]; //隊列中裝的元素final int FRONT = 0;//表示隊列的第一個元素int end; //用來表示隊列中的元素個數,指向隊列的最後一個元素//建構函式public PlotQue() {plots = new Plot[100];end = 0;}//添加元素public void add(Plot p) {plots[end] = p;// 把p加入到隊列中end++; //元素個數加一}//彈出元素public Plot pop() {//如果隊列為空白,直接返回nullif (end <= 0) {return null;}//彈出第一個元素Plot p = plots[FRONT];//把彈出去的元素的位置補上,所有隊列元素往前面移一位if (end > 1) {for (int i = 0; i < end; i++) {plots[i] = plots[i + 1];}}end--;//元素個數減一return p; //返回元素p}//判斷隊列是否為空白public boolean isEmpty() {if (end == 0) {return true;}return false;}}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
hdu1241詳解 Java廣搜搞定