问题描述
问题陈述:编写算法以查找填充完整图片/存储桶所需的最大笔画数。 约束:
- 一个笔触可以填充相邻的单元格(左,右,上,下),但不能填充对角线。
- 给出的是字符串列表,函数应返回最大笔画数的int值以填充完整的图片/存储桶。
static int fillBucket(List<String> picture){}
Sample Input:
1. picture = ["aaaba","ababa",a"aaaca"],Output: 5
2. picture = ["bbba","abba","acaa","aaac"],Output: 4
存储桶应如何填充的示例:
解决方法
您可以使用简单的洪水填充算法解决此问题:
public int fill(List<String> picture) {
// convert to char array to be sure to have O(n*m) complexity
// if the list is a linked list the complexity would be worse
char[][] arr = new char[picture.size()][];
int index = 0;
for (String s : picture)
arr[index++] = s.toCharArray();
int count = 0;
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
if (arr[i][j] != '-') { // '-' indicates visited
fill(arr,arr[i][j],i,j);
count++;
}
return count;
}
private void fill(char[][] arr,char c,int i,int j) {
if (arr[i][j] != c)
return;
arr[i][j] = '-';
if (i - 1 >= 0)
fill(arr,c,i - 1,j);
if (j - 1 >= 0)
fill(arr,j - 1);
if (i + 1 < arr.length)
fill(arr,i + 1,j);
if (j + 1 < arr[i].length)
fill(arr,j + 1);
}