Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 13, 2017 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/bd81ec1dfe46bd241bc1071766303929 to your computer and use it in GitHub Desktop.
Save jianminchen/bd81ec1dfe46bd241bc1071766303929 to your computer and use it in GitHub Desktop.
Leetcode 547 - Friend circles - using DFS search
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode547_FriendCircles
{
/// <summary>
/// Leetcode 547 -
/// https://leetcode.com/problems/friend-circles/#/description
/// </summary>
class Program
{
static void Main(string[] args)
{
}
public int FindCircleNum(int[,] M)
{
if (M.GetLength(0) == 0 || M.GetLength(1) == 0)
{
return 0;
}
int rows = M.GetLength(0);
int cols = M.GetLength(1);
var visit = new bool[rows];
int count = 0;
for (int row = 0; row < rows; row++)
{
if (visit[row])
{
continue;
}
visit[row] = true;
findCircleNumHelp(M, visit, row);
count++;
}
return count;
}
/// <summary>
/// depth first search - mark the row visited
/// </summary>
/// <param name="numbers"></param>
/// <param name="visit"></param>
/// <param name="row"></param>
private static void findCircleNumHelp(int[,] numbers, bool[] visit, int row)
{
int cols = numbers.GetLength(1);
for (int col = 0; col < cols; col++)
{
var current = numbers[row, col];
if (current == 0 || visit[col])
{
continue;
}
visit[col] = true;
findCircleNumHelp(numbers, visit, col);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment