百度编程题:BigHouse,小区最大连通数目

看了一下题目,没时间AC了,只写了部分代码,刚继续完成了。
用了一个全局变量,自己用了几个测试通过了,但不知道能不能AC,求大神解答

2个for循环,一次遍历矩阵每一个值,然后取最大连通数即可
int count = 0;
//返回值+1,因为还要加上自己
int find(int **grid, int ** flag,int n, int m, int row, int col)
{
	if (flag[row][col] == 0)
	{
		return 0;
	}
	flag[row][col] = 0;
		
	if ((row + 1) < n && flag[row + 1][col] && grid[row + 1][col])
	{
		::count=1 + find(grid, flag, n, m, row + 1, col);
	}
	if ((col + 1) < m && flag[row][col + 1] && grid[row][col + 1])
	{
		::count = 1 + find(grid, flag, n, m, row, col + 1);
	}
	if ((row - 1) >= 0 && flag[row - 1][col] && grid[row - 1][col])
	{
		::count = 1 + find(grid, flag, n, m, row - 1, col);
	}
	if ((col - 1) >= 0 && flag[row][col - 1] && grid[row][col - 1])
	{
		::count = 1 + find(grid, flag, n, m, row, col - 1);

	}
	return ::count;
}

#百度#
全部评论
***,百度这南京地区就出了这题。
点赞
送花
回复
分享
发布于 2016-09-21 08:08
用动态规划很好解
点赞
送花
回复
分享
发布于 2016-09-21 08:10
滴滴
校招火热招聘中
官网直投
import java.util.Arrays; public class MatrixConcat { public static void main(String[] args) { int[][] array={{0,1,0,1},{1,0,1,0},{0,1,1,0}}; int rows = 3; int cols = 4; int[] counts= new int[2]; boolean[] visited=new boolean[rows*cols]; for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ path(array,i,j,rows,cols,visited,counts); counts[1]=Math.max(counts[0], counts[1]); counts[0]=0; Arrays.fill(visited,false); } } System.out.println(counts[1]); } public static void path(int[][] array,int row,int col,int rows,int cols, boolean[] visited,int[] counts){ if(row>=0&&col>=0&&row<rows&&col<cols&&array[row][col]==1&&!visited[row*cols+col]){ visited[row*cols+col]=true; counts[0]+=1; path(array,row+1,col,rows,cols,visited,counts); path(array,row-1,col,rows,cols,visited,counts); path(array,row,col+1,rows,cols,visited,counts); path(array,row,col-1,rows,cols,visited,counts); } return; } }
点赞
送花
回复
分享
发布于 2016-09-25 18:59
我是用向外递归,通过了所有的测试用例
点赞
送花
回复
分享
发布于 2016-09-25 22:17

相关推荐

点赞 评论 收藏
转发
点赞 4 评论
分享
牛客网
牛客企业服务