搜索算法(三)--DFS/BFS求解宝岛探险问题(JAVA )
寶島探險問題
問題描述:某片海域有諸多島嶼,用0表示海洋,1-9表示陸地,現給定一個島嶼上的坐標點,求解所在島嶼的面積
思路:顯然這是一個搜索算法,即只要從當前坐標點開始遍歷,每遍歷到一個點進行計數即可,但是要注意sum的初始值為1!!!
Input:
10 10
1 2 1 0 0 0 0 0 2 3
3 0 2 0 1 2 1 0 1 2
4 0 1 0 1 2 3 2 0 1
3 2 0 0 0 1 2 4 0 0
0 0 0 0 0 0 1 5 3 0
0 1 2 1 0 1 5 4 3 0
0 1 2 3 1 3 6 2 1 0
0 0 3 4 8 9 7 5 0 0
0 0 0 3 7 8 6 0 1 2
0 0 0 0 0 0 0 0 1 0
6 8
Output:
38
DFS
import java.util.Scanner;public class DFS {static int[][] a = new int[50][50];static int[][] book = new int[50][50];static int sum = 1;static int n, m;static Scanner input = new Scanner(System.in);public static void main(String[] args) {n = input.nextInt();m = input.nextInt();for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {a[i][j] = input.nextInt();}}int startX = input.nextInt();int startY = input.nextInt();book[startX][startY] = 1;dfs(startX, startY);System.out.println(sum);}public static void dfs(int x, int y) {int[][] next = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};int tx, ty;for (int i = 0; i < 4; i++) {tx = x + next[i][0];ty = y + next[i][1];if(tx < 0 || tx > n - 1 || ty < 0 || ty > n - 1) {continue;}if (a[tx][ty] > 0 && book[tx][ty] == 0) {sum ++;book[tx][ty] = 1;dfs(tx, ty);}}return;} }BFS
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner;class node {int x;int y;node(int x, int y) {this.x = x;this.y = y;} } public class BFS {static int[][] a = new int[50][50];static int[][] book = new int[50][50];static int n, m;static int sum = 1;static Queue<node> queue = new LinkedList<>();static Scanner input = new Scanner(System.in);public static void main(String[] args) {n = input.nextInt();m = input.nextInt();for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {a[i][j] = input.nextInt();}}int startX = input.nextInt();int startY = input.nextInt();queue.offer(new node(startX, startY));book[startX][startY] = 1;bfs();System.out.println(sum);}public static void bfs() {int[][] next = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};int tx, ty;while (!queue.isEmpty()) {for (int i = 0; i < 4; i++) {tx = queue.peek().x + next[i][0];ty = queue.peek().y + next[i][1];if (tx < 0 || tx > n - 1 || ty < 0 || ty > n - 1) {continue;}if(a[tx][ty] > 0 && book[tx][ty] == 0) {queue.offer(new node(tx, ty));sum++;book[tx][ty] = 1;}}queue.remove();}return;} }拓展:漫水填充法(FloodFill)
問題: 要求解區域中總共有多少島嶼??
思路:對每個點進深搜,對于每個大于0的點進行填充負值,負值每次-1,最后輸出正的這個值,即是島嶼個數。
Input:
10 10
1 2 1 0 0 0 0 0 2 3
3 0 2 0 1 2 1 0 1 2
4 0 1 0 1 2 3 2 0 1
3 2 0 0 0 1 2 4 0 0
0 0 0 0 0 0 1 5 3 0
0 1 2 1 0 1 5 4 3 0
0 1 2 3 1 3 6 2 1 0
0 0 3 4 8 9 7 5 0 0
0 0 0 3 7 8 6 0 1 2
0 0 0 0 0 0 0 0 1 0
Output:
總結
以上是生活随笔為你收集整理的搜索算法(三)--DFS/BFS求解宝岛探险问题(JAVA )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前台一键备份数据库+PHP实现方式
- 下一篇: MAC 更新 PHP 指南 以及 PHP