Created
July 13, 2017 23:52
-
-
Save jianminchen/bd81ec1dfe46bd241bc1071766303929 to your computer and use it in GitHub Desktop.
Leetcode 547 - Friend circles - using DFS search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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