Hackerrank Connected Cell in a Grid

Problem Statement

You are given a matrix with m rows and n columns of cells, each of which contains either 1or 0. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally. The connected and filled (i.e. cells that contain a 1) cells form aregion. There may be several regions in the matrix. Find the number of cells in the largest region in the matrix.

Input Format
There will be three parts of t input:
The first line will contain m, the number of rows in the matrix.
The second line will contain n, the number of columns in the matrix.
This will be followed by the matrix grid: the list of numbers that make up the matrix.

Output Format
Print the length of the largest region in the given matrix.

Constraints
0<m<10
0<n<10

Sample Input:

4
4
1 1 0 0
0 1 1 0
0 0 1 0
1 0 0 0

Sample Output:

5

Task: 
Write the complete program to find the number of cells in the largest region.

Explanation

X X 0 0
0 X X 0
0 0 X 0
1 0 0 0

The X characters indicate the largest connected component, as per the given definition. There are five cells in this component.

思路分析:这题是Hackerrank一次的比赛题目,也是G公司一次面试中出现的面试原题。要在一个矩阵中找到最大的连通区域。基本可以用DFS搜索解决,在每个位置重启搜索找连通区域,一共有8个方向/分支,贪心保留最大cell数目。用visited标记数组记录已经count过的位置进行剪枝加速。是一道中规中矩的考察DFS/BFS搜索的题目。

AC Code

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

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

	static int cellCounter = 0;

	public static void main(String[] args) throws NumberFormatException, IOException {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
		DataInputStream in = new DataInputStream(new BufferedInputStream(System.in));
		int m = Integer.valueOf(in.readLine());
		int n = Integer.valueOf(in.readLine());
		int [][] matrix = new int [m][n];
		for(int i = 0; i < m; i++){
			String line = in.readLine();
			for(int j = 0; j < n; j++){
				matrix[i][j] = Integer.valueOf(line.split(" ")[j]);
			}
		}
		int maxNum = findMaxConnectedCellNum(matrix, m, n);
		System.out.println(maxNum);
    }

	private static int findMaxConnectedCellNum(int[][] matrix, int m, int n) {
		// TODO Auto-generated method stub
		int [][] visited = new int[m][n];
		int maxNum = 0;
		for(int i = 0; i < m; i++){
			for(int j = 0; j < n; j++){
				dfs(matrix, visited, i, j, m, n);
				if(cellCounter > maxNum) maxNum = cellCounter;
				cellCounter = 0;
			}
		}
		return maxNum;
	}

	private static void dfs(int[][] matrix, int[][] visited, int i, int j,
			 int m, int n) {
		// TODO Auto-generated method stub
		if(i < 0 || i >= m || j < 0 || j >= n){
			return;
		}
		if(visited[i][j] == 1 || matrix[i][j] == 0) return;
		cellCounter++;
		visited[i][j] = 1;
		for(int di = 0; di < 8; di++){
			dfs(matrix, visited, i + actionCosts[di][0], j + actionCosts[di][1], m, n);
		}
	}
}
时间: 2025-01-05 02:51:35

Hackerrank Connected Cell in a Grid的相关文章

MFC Grid control 2.27

MFC Grid control author:songyanwu MFC Grid control属性介绍: The control features: Cell selection using the mouse, with optional Control and Shift key combinations. Selection can be disabled. Row and Column resizing. Sizing can be disabled for row, column

N-Dimensional Grid

You are given an n-dimensional grid in which the dimensions of the grid are a1?×?a2?×?...?×?an. Each cell in the grid is represented as an n-tuple (x1,?x2,?...,?xn) (1?≤?xi?≤?ai). Two cells are considered to be adjacent if the Manhattan Distance betw

[LeetCode 1368] Minimum Cost to Make at Least One Valid Path in a Grid

Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 

POJ 3620 Avoid The Lakes (求连接最长的线)(DFS)

Description Farmer John's farm was flooded in the most recent storm, a fact only aggravated by the information that his cows are deathly afraid of water. His insurance agency will only repay him, however, an amount depending on the size of the larges

Avoid The Lakes

Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu Submit Status Description Farmer John's farm was flooded in the most recent storm, a fact only aggravated by the information that his cows are deathly afraid of water. His ins

ACM学习历程—BNUOJ3685 Building for UN(构造)

The United Nations has decided to build a new headquarters in Saint Petersburg, Russia. It will have a form of a rectangular parallelepiped and will consist of several rectangular floors, one on top of another. Each floor is a rectangular grid of the

POJ 3566

 Building for UN Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 1367   Accepted: 599   Special Judge Description The United Nations has decided to build a new headquarters in Saint Petersburg, Russia. It will have a form of a rectangu

[深度优先搜索] POJ 3620 Avoid The Lakes

Avoid The Lakes Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8173   Accepted: 4270 Description Farmer John's farm was flooded in the most recent storm, a fact only aggravated by the information that his cows are deathly afraid of wate

IOI 2009:Mecho

IOI2009 Mecho Time Limit: 10000ms Memory Limit: 262144KB This problem will be judged on SPOJ. Original ID: CTOI09_164-bit integer IO format: %lld      Java class name: Main Prev Submit Status Statistics Discuss Next Type: None None Graph Theory 2-SAT