200. Number of Islands(深搜)

package Union_Find;

public class NumIslands_200 {
	// 200. Number of Islands
	/*
	 * Given a 2d grid map of '1's (land) and '0's (water), count the number of
	 * islands. An island is surrounded by water and is formed by connecting
	 * adjacent lands horizontally or vertically. You may assume all four edges of
	 * the grid are all surrounded by water.
	 * 
	 * Example 1:
	 * 
	 * Input: 11110 11010 11000 00000
	 * 
	 * Output: 1
	 * 
	 * Example 2:
	 * 
	 * Input: 11000 11000 00100 00011
	 * 
	 * Output: 3
	 * 
	 * 來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/number-of-islands
	 * 著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
	 */

	public static void main(String[] args) {
		NumIslands_200 n = new NumIslands_200();
		char[][] grid = { { '1', '1', '1', '1', '0' }, { '1', '1', '0', '1', '0' }, { '1', '1', '0', '0', '0' },
				{ '0', '0', '0', '0', '0' } };
		System.out.println(n.numIslands(grid));
	}

	// 用數組表示上下左右四個方向
	private static final int[][] directions = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };

	// 標記是否被訪問
	private boolean[][] isMarked;

	private int row;
	private int col;

	private char[][] grid; // 設爲全局,方便使用

	public int numIslands(char[][] grid) {
		int count = 0;
		row = grid.length;
		if(row==0) {
			return 0;
		}
		col = grid[0].length;
		this.grid=grid;
		isMarked = new boolean[row][col];
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				if (!isMarked[i][j] && grid[i][j] == '1') {
					count++;
					dfs(i, j);
				}

			}
		}

		return count;

	}

	private void dfs(int i, int j) {
		isMarked[i][j] = true;
		// 四個方向進行深搜
		for (int k = 0; k < 4; k++) {
			int newX = i + directions[k][0];
			int newY = j + directions[k][1];
			if (inArea(newX, newY) && !isMarked[newX][newY] && grid[newX][newY] == '1') {
				dfs(newX,newY);
			}
		}
	}

	private boolean inArea(int newX, int newY) {

		return newX >= 0 && newY >= 0 && newX < row && newY < col;
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章